在 jQuery 中使用 contains() 匹配多个关键字
Matching multiple keywords using contains() in jQuery
当前正在使用 contains() 匹配特定关键字。我如何扩展它以包含多个关键字?
尝试过使用 || (or) 运算符,但没有快乐。
<!-- Product names include Apple iPad, Acer Iconia, Lenovo Thinkpad -->
<h1 id="pbtitle">Apple iPad 3</h1>
<div class="install_option" style="display:none;">
<div style="box-sizing:border-box; float:left;">
<a href="https://www.exmaple.com/acc" target="_blank">
<h3 style="font-weight:bold;">Would you like to view accessories?</h3>
</a>
</div>
</div>
$(".install_option").each(function() {
if($("h1#pbtitle:contains:contains('Acer' || 'Lenovo' || Apple )").length>0){
$('.install_option').css('display','block');
}
});
这样做
if($("h1#pbtitle:contains('Acer'),h1#pbtitle:contains('Lenovo'),h1#pbtitle:contains('Apple')").length>0)
使用JavaScript函数indexOf()
工作示例 jsfiddle
var options = ['Acer','Lenovo','Apple']; // options that you want to look for
var text = $("#pbtitle").text(); // string where you want to look in
options.forEach( function( element ) {
if ( text.indexOf( element ) != -1 ) { // if its NOT -1 (-1 = not found)
alert( 'found' ); // then we found it .. do your magic
}
})
冒险有点超出问题范围,我猜产品列表是同类产品的动态。
在这种情况下,最好在产品标签中添加 属性,例如:
<h1 id="pbtitle" has_install_option="true">Apple iPad 3</h1>
var condition = $('h1#pbtitle').attr('has_install_option') == 'true';
并检查循环中的条件。
[想一想您将拥有带有 install_option 的 Apple 产品或 Appleseed 产品的那一天...]
p.s 在此示例中,最好将条件放在循环之外,因为条件相对于循环元素是静态的
当前正在使用 contains() 匹配特定关键字。我如何扩展它以包含多个关键字? 尝试过使用 || (or) 运算符,但没有快乐。
<!-- Product names include Apple iPad, Acer Iconia, Lenovo Thinkpad -->
<h1 id="pbtitle">Apple iPad 3</h1>
<div class="install_option" style="display:none;">
<div style="box-sizing:border-box; float:left;">
<a href="https://www.exmaple.com/acc" target="_blank">
<h3 style="font-weight:bold;">Would you like to view accessories?</h3>
</a>
</div>
</div>
$(".install_option").each(function() {
if($("h1#pbtitle:contains:contains('Acer' || 'Lenovo' || Apple )").length>0){
$('.install_option').css('display','block');
}
});
这样做
if($("h1#pbtitle:contains('Acer'),h1#pbtitle:contains('Lenovo'),h1#pbtitle:contains('Apple')").length>0)
使用JavaScript函数indexOf()
工作示例 jsfiddle
var options = ['Acer','Lenovo','Apple']; // options that you want to look for
var text = $("#pbtitle").text(); // string where you want to look in
options.forEach( function( element ) {
if ( text.indexOf( element ) != -1 ) { // if its NOT -1 (-1 = not found)
alert( 'found' ); // then we found it .. do your magic
}
})
冒险有点超出问题范围,我猜产品列表是同类产品的动态。 在这种情况下,最好在产品标签中添加 属性,例如:
<h1 id="pbtitle" has_install_option="true">Apple iPad 3</h1>
var condition = $('h1#pbtitle').attr('has_install_option') == 'true';
并检查循环中的条件。 [想一想您将拥有带有 install_option 的 Apple 产品或 Appleseed 产品的那一天...]
p.s 在此示例中,最好将条件放在循环之外,因为条件相对于循环元素是静态的