2

我正在尝试根据用户先前单击的单独图像来检索图像的来源。

<div class="card1">
    <div>
    <a href="#" class="quickFlipCta"><img class="back" src="Memory Pals/Test Pictures/QuestionMark.gif" /></a>
    </div>

    <div>
    <a href="#" class="quickFlipCta"><img class="front" src="Memory Pals/Test Pictures/flower.gif" /></a>
    </div>
</div>

<div class="card2">
    <div>
    <a href="#" class="quickFlipCta"><img class="back" src="Memory Pals/Test Pictures/QuestionMark.gif" /></a>
    </div>

    <div>
    <a href="#" class="quickFlipCta"><img class="front" src="Memory Pals/Test Pictures/flower.gif" /></a>
    </div>
</div>

在我的具体示例中,我试图在单击“后”时检索“前”的来源。此外,它必须在同一张卡片中检索“front”的来源。

这是我尝试过的,但我无法让它工作:

$(document).ready(function(){

        var found = 0;
        var last = null;

        $('img').each(function(index){
          $(this).attr('id','img-' + index);
        });    

        $('img').click(function(){
          if( last ) {
            if( ($(this).attr('src') == last.attr('src')) ) {
              $(this).css('visibility', 'hidden');
              last.css('visibility', 'hidden');
              found++;
            }
            if (found == 3) {
            window.location.href = "#play2"; 
            location.reload(); //resets found to 0
            }
            last = null;
          } else {
            last = $(this);
          }
        });

我意识到它不是检索“正面”的来源,而是检索用户点击的图像的来源。如何更改它以便在单击“后”时检索“前”的来源?

4

2 回答 2

2

以下内容可能会为您指明正确的方向:

$('img.back').click(function () {
    var frontSrc = $('img.front').first().attr('src');
    alert('The source for \'front\' is ' + frontSrc);
    }
}); // end .click handler

使用hasClassjQuery 函数来确定您单击的元素是否具有 'back' 类。然后使用img.front选择器找到带有前端类的图像并检索它的源。

于 2012-07-06T16:25:44.483 回答
1

这是你要找的吗?

$('img').click(function(){
    console.log($(this)
           .closest('div[class*=card]') // <-- get closest div with class containing card
           .find('div > a > img') // <-- find all img under that div
           .not(this) // <-- filter out the clicked one
           .attr('src')); // <-- get src of the image not clicked under same div with class containing card
});​

http://jsfiddle.net/gweVT/

于 2012-07-06T16:29:33.790 回答