javascript - 单击链接时如何选择同级元素?

标签 javascript jquery

我有几个链接按钮,以便在其下面显示一个 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/

相关文章:

php - 捕获YouTube播放器的开始按钮和观看的秒数

javascript - 为什么 FireFox window.onbeforeunload() 仅在显示确认对话框时触发?

javascript - 用于移动菜单的简单 jQuery 左/右滑动切换动画

javascript - 在表格的第一行上方添加一个新行

javascript - AJAX/PHP 多表单 POST 提交

javascript - 无法使用 Angular.js/JavaScript 通过 jQuery 序列化方法获取禁用的下拉字段值

javascript - HTML 页面部分的小 map 在视口(viewport)中显示为固定 anchor

javascript - 复制剪贴板功能在本地工作但在服务器上不工作

jquery - 固定列宽

javascript - 悬停时链接 alt 出现在单独的 div 中