无法让 jQuery .each() 工作



我在页面的三个部分中有以下HTML代码:

<div class="pjesmarrje">
    <a href="#" onclick="window.open('https://www.facebook.com/sharer/sharer.php?u='+encodeURIComponent(location.href),'facebook-share-dialog','width=626,height=436'); return false;">
        <div></div>
        <span>Kliko këtu për pjesëmarrje</span>
    </a>
</div>

而且,当div点击时,我正在尝试更改其内部的背景图像。我得到了这个jQuery代码:

$(document).ready(function() {
    $(".pjesmarrje").click(function() {
        $(".pjesmarrje div").css("background-image", "url(images/mumanin_s2.png)");
    });
});

当我点击其中一个元素时,所有其他元素的背景图像也会发生变化。我不希望这种情况发生,我希望bg图像只有在单击特定元素时才会更改。我试着使用.ech()函数,但没有成功。

感谢您的帮助。谢谢

您正在失去所谓的范围。如果你想让它在特定的.pjesmarrje中工作,你需要类似的东西:

$(document).ready(function() {
    $(".pjesmarrje").click(function() {
        // `this` is a reference to the `.pjesmarrje` that triggered the click
        // event. and, within that `<div>` we want to find the `<div>` whose
        // background we want to change.
        $("div", this).css("background-image", "url(images/mumanin_s2.png)");
    });
});

注意第二个参数:$(selector, scope)。这意味着我们只关心点击的.pjesmarrje中的<div>(而不是页面上的所有内容)。

值得思考的是:$('div', this)$(this).find('div')同义。

$(document).ready(function () {
    $(".pjesmarrje").click(function () {
        $(this).find("div").css("background-image", "url(images/mumanin_s2.png)");
    });
});

最新更新