如何在具有逗号分隔属性值的元素上运行"foreach"循环?



我正在尝试比较两个元素的值,如果它们共享该值,请对其中一个执行.css((修饰符。问题是,我的一些比较元素的值在逗号分隔的列表中:正常值:";400〃"500〃;逗号值";600、602"502、504";

我的jQuery如下:

jQuery('#container1 > div[booth-number="{Booth Assignments}"]').css('background-color','white')

正如你所看到的,我正在使用合并标签来指示我希望修改其背景颜色的展位。

我也在尝试类似forEach循环的东西:

const booths = [{Booth Assignments}]
booths.forEach(jQuery('container1 > div[booth-number=jQuery(this)]').css('background-color', 'white')

这似乎也不起作用。真的需要一些帮助!

首先,您可以获取数组并用逗号连接它,替换空格,然后在逗号上拆分它。这将允许您循环浏览项目。

接下来,我将使用一个数据属性,因为展位号无效。

由于您使用的是jquery,我也只是使用$.each

let booths = ["600, 602", "502, 504"].join(",").replace(/[s]/g, "").split(",");
$.each(booths,function(index,booth) {
$('#container1 > div[data-booth-number="' + booth + '"]').css('background-color', 'red')
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container1">
<div data-booth-number="600">608</div>
</div>

foreach语法不正确。

const booths = ["this", "is", "dummy", "data", "and,some,more", "dummier,datas"].join(",").replace(/[s]/g, "").split(",");
console.log("All booths: ");
console.log(booths);
console.log(" ");  // Blank line for readability
booths.forEach(function(booth_number) {
$('container1 > div[booth-number=' + booth_number + ']').css('background-color', 'white');
console.log("This should color booth "" + booth_number + "" white.");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

最新更新