jQuery获取同级或最接近的元素不起作用

jQuery get sibling or closest element not working

本文关键字:元素 不起作用 最接近 获取 jQuery      更新时间:2023-09-26

我就是无法让这一小段代码正常工作。我基本上是想得到点击的ahref的兄弟,但它只是返回点击的元素本身(使用console.log()来测试这一点)。

$('.script-vote').click(function(e) {
    e.preventDefault();
    var href = $(this);
    href.siblings('.script-vote') //This doesn't work
        .removeClass('active');
    href.closest('.script-vote') //This doesn't work
        .removeClass('active');
});

还有我的HTML:

<div class="one-half t-center">
    <a href="..." class="script-vote up" title="Upvoten">
        <i class="fa fa-thumbs-o-up"></i>
        <span class="score"><?=$post->getUpVotes()?></span>
    </a>
</div>
<div class="one-half t-center">
    <a href="..." class="script-vote down" title="Downvoten">
        <i class="fa fa-thumbs-o-down"></i>
        <span class="score"><?=$post->getUpVotes()?></span>
    </a>
</div>

因此,当我单击.script-vote.up元素时,我想删除.script-vote.downactive类。提前谢谢。

;a> HTML中的元素没有任何同级元素。但他们的父母会这样做。确保他们被封装在一个grand-parentdiv:中

<div class="voting-container">
<div class="one-half t-center">
    <a href="..." class="script-vote up" title="Upvoten">
       <i class="fa fa-thumbs-o-up"></i>
        <span class="score"><?=$post->getUpVotes()?></span>
    </a>
</div>
<div class="one-half t-center">
    <a href="..." class="script-vote down" title="Downvoten">
        <i class="fa fa-thumbs-o-down"></i>
        <span class="score"><?=$post->getUpVotes()?></span>
    </a>
</div>
</div>

您可以使用jQuery参考以下JavaScript作为示例:

$(".script-vote").click(function(){
    var otherVotingButton = $(this).parent().siblings(".one-half").first().find(".script-vote");
    otherVotingButton.css("background-color","red");     
    otherVotingButton.href="#";
    otherVotingButton
        .off() //remove original event handler
        .click(function() { alert("you already voted!");});
});

获取父级的兄弟姐妹,然后获取脚本投票<a> 元素。