我想将所有字符串放在一个数组中然后查看jquery选择器是否包含任何这些stings,如果是,请执行一些代码。
创建我的数组:
var usa_destinos_direct = ["York-Todos", "York-EWR", "Florida-Fort", "Florida-Todos", "Los Angeles", "Oakland" ];
然后检查它是否在jquery选择器中:
if ($("div.pagetitlebox h1:contains(usa_destinos_direct)")){
$("div").css("background", "yellow");
}
我哪里错了?
答案 0 :(得分:1)
jQuery不会将usa_destinos_direct
视为变量,而是将您想要在h1中搜索的字符串。
您应该遍历目标数组:
usa_destinos_direct.forEach(function (str) {
if ($("div.pagetitlebox h1:contains(" + str + ")")){
$("div").css("background", "yellow");
}
};
答案 1 :(得分:0)
您可以映射该数组以构建所需的选择器:
var containsSelector = usa_destinos_direct.map(d => `h1:contains('${d}')`).join(',');
var usa_destinos_direct = ["York-Todos", "York-EWR", "Florida-Fort", "Florida-Todos", "Los Angeles", "Oakland" ];
var containsSelector = usa_destinos_direct.map(d => `h1:contains('${d}')`).join(',');
$(`div.pagetitlebox ${containsSelector}`).css("background", "yellow");

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="pagetitlebox">
<h1>York-Todos</h1>
<h1>Florida-Fort</h1>
<h1>Venezuela</h1>
</div>
&#13;