单击链接时如何选择兄弟元素?

Jac*_*ang 0 javascript jquery

我有serval链接按钮,以显示它下面的div.

<a class="btnComment" onclick="showComment()" isshow='0'>{{ post_comments.count }} comment</a>
<div class="comment">
....
</div>
<a class="btnComment" onclick="showComment()" isshow='0'>{{ post_comments.count }} comment</a>
<div class="comment">
....
</div>
<a class="btnComment" onclick="showComment()" isshow='0'>{{ post_comments.count }} comment</a>
<div class="comment">
....
</div>
Run Code Online (Sandbox Code Playgroud)

我想克隆一个linkbutton,只显示它下面的div元素.但是我的js代码:

function showComment(){
                   var isshow=$(this).attr('isshow');
                   if(isshow=="0"){
                       this.$(".comment").show();
                       $(this).attr('isshow',"1");
                   }
                   else{
                       this.$(".comment").hide();
                       $(this).attr("isshow","0");
                   }
               }
Run Code Online (Sandbox Code Playgroud)

这个显示所有div.当我使用$(this).siblings()或$(this).next()时,我得到null,我不知道为什么不起作用.

我能做什么?

sro*_*oes 5

this如果在内联事件中运行它,则不指向该元素.请尝试以下方法:

onclick="showComment(this)"
Run Code Online (Sandbox Code Playgroud)

和:

           function showComment(el) {
               var isshow=$(el).attr('isshow');
               if(isshow=="0"){
                   $(el).next(".comment").show();
                   $(el).attr('isshow',"1");
               }
               else{
                   $(el).next(".comment").hide();
                   $(el).attr("isshow","0");
               }
           }
Run Code Online (Sandbox Code Playgroud)

或者如果你使用jQuery click,你可以this用来指向元素:

$('.btnComment').click(function(event) {
    var isshow=$(this).attr('isshow');
    if(isshow=="0"){
        $(this).next(".comment").show();
        $(this).attr('isshow',"1");
    }
    else{
        $(this).next(".comment").hide();
        $(this).attr("isshow","0");
    }
});
Run Code Online (Sandbox Code Playgroud)