如何使用jQuery find()结合正则表达式查找嵌套图标类
解决方案
问题背景
我有内部嵌套图标的div元素,想通过find()方法判断其中属于4种图标类型(led-green/led-yellow/led-red/led-null)中的哪一种,能不能用find()结合正则表达式来获取对应的类?
对应的HTML结构:
<div id="a" class="tile"> <span> <span> <i class="led-red"></i> Led Red </span> </span> </div> <div id="b" class="tile"> <span> <span> <i class="led-green"></i> Led Green </span> </span> </div> <div id="c" class="tile"> <span> <span> <i class="led-yellow"></i> Led Yellow </span> </span> </div>
原尝试的JavaScript代码:
var rexValues = /(led-green|led-yellow|led-red|led-null)/; //如果元素a本身带有该类,此方法可行, //但由于类嵌套在内部,我需要使用find() var aclass = a.className.match(rexValues); //我想要实现类似这样的功能 var aclass = $(a).find(rexValues);
实现方法
jQuery的find()方法不支持直接传入正则表达式作为选择器,但可以通过以下方式实现需求:
方法1:定位内部元素后用正则匹配class
先通过find()找到嵌套的<i>元素,再用正则提取目标类:
var rexValues = /(led-green|led-yellow|led-red|led-null)/; // 处理单个tile元素(以id="a"为例) var $targetIcon = $('#a').find('i'); var matchedIconClass = $targetIcon.attr('class').match(rexValues)[0]; console.log(matchedIconClass); // 输出:led-red
方法2:批量处理所有tile元素
如果要遍历所有.tile元素并提取对应图标类,可以结合each()和filter():
var rexValues = /(led-green|led-yellow|led-red|led-null)/; $('.tile').each(function() { // 筛选出符合正则的i元素 var $matchedIcon = $(this).find('i').filter(function() { return rexValues.test($(this).attr('class')); }); var iconClass = $matchedIcon.attr('class').match(rexValues)[0]; // 这里可将iconClass用于后续排序逻辑 console.log(`元素${$(this).attr('id')}的图标类:${iconClass}`); });
结合排序需求的完整实现
参考排序逻辑,我们可以给不同图标类定义权重,再对.tile元素排序:
var rexValues = /(led-green|led-yellow|led-red|led-null)/; // 定义排序权重:绿色优先,其次黄色、红色,最后null var iconSortWeight = { 'led-green': 1, 'led-yellow': 2, 'led-red': 3, 'led-null': 4 }; // 执行排序并重新插入DOM $('.tile').sort(function(a, b) { var aIconClass = $(a).find('i').attr('class').match(rexValues)[0]; var bIconClass = $(b).find('i').attr('class').match(rexValues)[0]; return iconSortWeight[aIconClass] - iconSortWeight[bIconClass]; }).appendTo($('.tile').parent());
内容的提问来源于stack exchange,提问作者Seltonu
相关产品推荐
相关产品推荐

