简体   繁体   English

我如何在这个元素中添加 class 或 id 只知道有多个元素包含“.side-sections .widget”

[英]How do I add class or id in this element just knowing that there is more than one element containing " .sided-sections .widget "

var b = ('data-type');

if ($(b + ":contains('cover')")) {
  $(".sided-sections .widget").addClass("cate-cover")
}

i want repair this code please because when I add this code it adds a class to all elements that contain " .sided-sections .widget " so I want to dedicate something to that where the class adds on data-type='cover' only and thank you我想修复此代码,因为当我添加此代码时,它会向所有包含“.side-sections .widget”的元素添加一个类,所以我想专门用于该类仅添加 data-type='cover' 的内容谢谢

A jQuery selector doesn't return a true/false value that can be used in .match() . jQuery 选择器不会返回可在.match()使用的true/false值。 If you want to know if a selector finds anything, you need to get its length.如果你想知道一个选择器是否找到了任何东西,你需要得到它的长度。

Furthermore, if doesn't set this to the elements that the selector matches.此外, ifthis设置为选择器匹配的元素。 If you want to set this , you need to use .each() to loop over all the matching elements.如果你想设置this ,你需要使用.each()来循环所有匹配的元素。

$(b + ":contains('cover')").each(function() {
    $(this).siblings(".sided-sections .widget").addClass("cate-cover");
});

But you don't even need that, because you can apply .siblings() directly to the selector:但您甚至不需要它,因为您可以将.siblings()直接应用于选择器:

$(b + ":contains('cover')").siblings(".sided-sections .widget").addClass("cate-cover");

If this doesn't work, add the HTML to your question, and point out which elements should get the cate-cover class.如果这不起作用,请将 HTML 添加到您的问题中,并指出哪些元素应该获得cate-cover类。 You might have the relationships between the selectors wrong.您可能将选择器之间的关系弄错了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 你如何通过id选择多个元素? - How do you select more than one element by id? 如果每个值有多个,我如何根据其值从数组中仅删除一个元素 - How do I remove just one element from my array based on its value if there are more than one of each value 如何更改多个元素? - How do I change more than one element? jQuery UI:如果元素必须具有 id="selectable",我如何才能拥有多个“可选择”元素? - jQuery UI: How can I have more than one "selectable" element if the element has to have id="selectable"? 如何将多个子元素附加到父元素Javascript - How do I append more than one child element to a parent element Javascript 如何在不知道特定元素的类或ID的情况下将其定位为目标,但确实具有该元素的所有DOM详细信息 - How to target a specific element without knowing it's class or id, but do have all DOM details of the element 多次更改元素的ID - Changing id of an element more than one time 我如何正确使用此代码将所有出现的多个十进制元素替换为一个? - How do i properly use this code to replace all occurrences of more than one decimal element with a single one? pdfmake如何在一列中添加多个元素 - pdfmake how to add more than one element in a column 如何选择必须具有多个CSS类的元素? - How to select an element that must have more than one css class?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM