【问题标题】:Matching multiple keywords using contains() in jQuery在 jQuery 中使用 contains() 匹配多个关键字
【发布时间】:2017-09-09 09:31:31
【问题描述】:

当前使用 contains() 匹配特定关键字。如何扩展它以包含多个关键字? 尝试过使用 || (或)运算符,但没有乐趣。

<!-- 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');
    }
});

【问题讨论】:

标签: javascript jquery contains


【解决方案1】:

冒着有点超出问题范围的风险,我猜产品列表是动态的同类产品。 在这种情况下,最好向产品标签添加一个属性,例如:

<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 在此示例中,最好将条件放在循环之外,因为条件相对于循环元素是静态的

【讨论】:

    【解决方案2】:

    使用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
        }
    })
    

    【讨论】:

    • 这已经完成了工作,无论如何排除一个关键字,如通用?
    【解决方案3】:

    这样做

    if($("h1#pbtitle:contains('Acer'),h1#pbtitle:contains('Lenovo'),h1#pbtitle:contains('Apple')").length&gt;0)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-11-07
      • 1970-01-01
      • 1970-01-01
      • 2015-06-13
      • 2014-11-10
      • 1970-01-01
      • 2011-11-26
      相关资源
      最近更新 更多