首页 > 解决方案 > 找到最近的父 .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>

标签: javascriptjqueryhtml

解决方案


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”)。


推荐阅读