javascript - 找到最近的父 .classOne 或 .classTwo jquery
问题描述
我在同一页面中有两个不同的评论列表,第一个使用ul
和第二个dl
。
问题
单击时我想为两个元素着色button
我不想创建一个新变量。我想知道是否可能,例如:
var Comment = $(document).find("[data-href='post?s=" + id_comment + "']").closest("li.comment || dd.listed_comment");
使用OR
左右
$(document).on("click", 'button', function(){
var id_comment =$(this).data("id_comment");
var Comment = $(document).find("[data-href='post?s=" + id_comment + "']").closest("li.comment");
Comment.css("background","red");
});
li,dd{border:1px solid blue;margin:5px 0;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<ul class="comments">
<li class="comment"><div data-href='post?s=16'>Comment</div></li>
<li class="comment"><div data-href='post?s=25'>Comment</div></li>
<li class="comment"><div data-href='post?s=26'>Comment</div></li>
</ul>
<dl class="listed_comments">
<dd class="listed_comment"><div data-href='post?s=25'>Comment</div></dd>
<dd class="listed_comment"><div data-href='post?s=24'>Comment</div></dd>
</dl>
<button data-id_comment="25">Color red</button>
解决方案
jQuery 允许使用 CSS 选择器。CSS 的一部分是使用多个选择器,用逗号分隔。这使您可以轻松地选择其中一个。
$(document).on("click", 'button', function(){
var id_comment =$(this).data("id_comment");
var Comment = $(document).find("[data-href='post?s=" + id_comment + "']").closest("li.comment, dd.listed_comment");
Comment.css("background","red");
});
li,dd{border:1px solid blue;margin:5px 0;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<ul class="comments">
<li class="comment"><div data-href='post?s=16'>Comment</div></li>
<li class="comment"><div data-href='post?s=25'>Comment</div></li>
<li class="comment"><div data-href='post?s=26'>Comment</div></li>
</ul>
<dl class="listed_comments">
<dd class="listed_comment"><div data-href='post?s=25'>Comment</div></dd>
<dd class="listed_comment"><div data-href='post?s=24'>Comment</div></dd>
</dl>
<button data-id_comment="25">Color red</button>
当然,最简单的方法是跨两个元素使用一个公共类(例如,“comment-container”)。
推荐阅读
- python - 如何重新激活 django 服务器?
- r - 为什么这个带有 lambda 函数的管道不返回一个矩阵?
- javascript - 如何在不添加内联样式的情况下从 div 中删除特定的 css?
- pyspark - spark如何应用“仅正确”加入?
- r - 如何将导入的图像与其他 R 图结合起来?
- systemd - 如何在计算机进入之前让 systemd 自动设置 /sys/power/image_size(为 0)
- azure-active-directory - 如何强制用户使用 MSAL 角度的两因素身份验证?
- reactjs - React-Player 无法正确调整视频大小
- python - 在 python 中使用自定义替换创建 Vigenere 样式加密
- java - 如何找到两个数字之间的位移