[英]How do I check all list item ID's against a range of classes in a variable?
如果有人提出这个问题,请原谅。
我无法获取我的代码来检查ul class变量中每个可能的类选项的每个列表ID。
HTML:
<div class="category-filters-wrap">
<ul class="ULClasses"> /* dynamic options that may contain multiple class options */
<li id="Benefits">Item</li> /* Hard coded IDs */
<li id="Resources">Item</li>
<li id="Timecards">Item</li>
</ul>
</div>
jQuery的:
$('.category-filters-wrap').each(function() {
$(this).find('li').each(function() {
liID = $(this).attr('id'); /* Get ID from this list item */
ULClass = $(this)closest('ul').attr('class'); /* Get Classes from closest UL to this list item */
/* if the list ID matches ANY of the classes in the UL */
if ($ (liID).hasClass(ULClass) ) {
/* ... do stuff */
}
});
});
我已经尝试了一些类似的方法:
/* starting from if */
if (liID[1].match("(' + ULClass + ')") {
/* ... do stuff */
}
和
/* starting from if */
if ($(liID).is(":contains('" + ULClass + "')")) {
/* ... do stuff */
}
但是我想我现在只是把厨房水槽扔了。 在此先感谢您的帮助。 我对jQuery相对较新(如果我犯了一些严重的noobie错误,请原谅)。 如果您对我做错了什么有任何想法,可以提供更多详细信息来帮助我理解这一点,那就更好了!
格拉西亚斯!
您可以创建一个函数来迭代类名并返回找到的类名:
var searchClassName = function(string) {
var arrayClasses = string.split(" ");
for(var i = 0; i < arrayClasses.length; i++) {
if($('#'+arrayClasses[i]).length > 0) {
// the id with the className XXX was found!
return arrayClasses[i];
}
}
return false;
}
searchClassName("string of classnames space separated");
// returns false if doesn't found
// returns the name of the classname found with id
var searchClassName = function(string) { var arrayClasses = string.split(" "); for(var i = 0; i < arrayClasses.length; i++) { if($('#'+arrayClasses[i]).length > 0) { // the id with the className XXX was found! return arrayClasses[i]; } } return false; } alert(searchClassName("Benefits Resources Timecards"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <div class="category-filters-wrap"> <ul class="Benefits AnotherClassname"> <li id="Benefits">Item</li> <li id="Resources">Item</li> <li id="Timecards">Item</li> </ul> </div>
您当前的jquery使用find和close最接近。
为什么不让自己的生活变得更轻松,并为每个li标签分配一个类(例如称为“ myclass”),然后对它们进行检查? 当然,它的数据不是很长,而您的DOM页面很短,所以性能不是问题-但是根据良好实践,我会重新考虑您的寻求和寻找思维过程。 下面的示例将在您的页面上搜索所有具有“ myclass”类的li标记-当找到一个li标记时,它会检查li标记是否具有“ anotherclass”类,如果存在,则执行...
$('li.myclass').each(function() {
/* if the list ID matches ANY of the classes in the UL */
if ($(this).hasClass("anotherclass") ) {
/* ... do stuff */
}
});
});
或以下一个衬里将找到所有具有myclass和anotherclass的li标签,然后执行操作...
$('li.myclass.anotherclass').each(function() { /* do stuff */ });
我希望这个建议不会冒犯...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.