单击另一个图像时检索图像源?

时间:2012-07-06 16:14:06

标签: javascript jquery

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

<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>

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

这是我尝试过的,但我无法让它发挥作用:

$(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);
          }
        });

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

2 个答案:

答案 0 :(得分:2)

这可能会指向正确的方向:

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

使用hasClass jQuery函数来确定您点击的元素是否具有“后退”类。然后使用img.front选择器查找具有前端类的图像并检索它的源。

答案 1 :(得分: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/

相关问题