[英]How can I select an element which has only a specific class?
这是我的选择器:
doc.on("click", ".add_your_qora", function(e){
我的代码将选择以下内容:
<div class="add_your_qora"> whatever </div>
我的代码也会选择此代码:
<div class="add_your_qora another_class_name"> whatever </div>
我要做的就是避免这种情况。 不应选择第二个元素,因为它没有只有 add_your_qora
类。 我应该如何编写选择器?
检查当前元素Element.classList
长度是否大于1:
$(doc).on("click", ".add_your_qora", function(e) { if (this.classList.length > 1) return; console.log($(this).text()); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="doc"> <button class="add_your_qora">only add_your_qora</button> <button class="add_your_qora another_class">has another class as well</button> </div>
如果所需元素是此类的第一个元素,则可以使用document.querySelector('.add_your_qora')
,该方法将仅返回找到的与选择器匹配的第一个元素。
如果要选择具有add_your_qora
类的所有元素,但也具有another_class
的元素,则可以使用$('.add_your_qora:not(.another_class)')
。
如果要选择仅具有add_your_qora
类的所有元素,请使用此选择器[class=another_class]
另一种方式
$(function(){ $(document).on('click', '.add_your_qora', function(e){ if ($(this).attr('class').match(/^add_your_qora$/) == null) return; alert($(this).text()); }); });
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <div class="add_your_qora"> add_your_qora </div> <div class="add_your_qora another_class_name"> add_your_qora another_class_name </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.