我有几个链接按钮,以便在其下面显示一个 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>
我想点击一个链接按钮并只显示其下方的 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");
}
}
这显示所有div。当我使用 $(this).siblings() 或 $(this).next() 时,我得到 null,我不知道为什么这不起作用。
我能做什么?
最佳答案
如果您在内联事件中运行
this
,则它不会指向该元素。请尝试以下操作:
onclick="showComment(this)"
并且:
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");
}
}
或者如果你使用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");
}
});
关于javascript - 单击链接时如何选择同级元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18297344/