2017-04-13 140 views
0

當前匹配的關鍵字然後執行操作。如何將排除列表納入下面的功能?在jQuery中爲indexOf關鍵字匹配添加關鍵字排除

<!-- Product names include Apple iPad, Acer Iconia, Lenovo Thinkpad plus Generic, No Brand--> 
<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.example.com/acc" target="_blank"> 
      <h3 style="font-weight:bold;">Would you like to view accessories?</h3> 
     </a>  
    </div> 
</div> 
var options = ['Acer','Apple','Lenovo']; 
var exclusions = ['Generic','No Brand']; 
var text = $("#pbtitle").text(); 

options.forEach(function(element) { 
    if (text.indexOf(element) != -1) { // if its NOT -1 (-1 = not found)  
     $('.install_option').css('display','block'); // then we found it .. do your magic 
    } 
}); 

回答

0

如果文本必須是夾雜物/排除的子字符串,然後

if (options.indexOf(text) != -1 && exclusions.indexOf(text) == -1) 

你需要嘗試

var options = ['Cooker hood','Island','Ceiling','Downdraft','Integrated','Canopy','Telescopic','Cabair','Bathroom']; 
var exclusions = ['Filters','Filter','Kit','Foil','Ducting','Switch','Transformer','Silencers', 'Install']; 
var text = $("#pbtitle").text(); 
if (options.indexOf(text) != -1 && exclusions.indexOf(text) == -1) 
{ 
    $('.install_option').css('display','block'); 
} 
else 
{ 
    $('.install_option').css('display','none'); 
} 
+1

排除應該是'== -1' –

+0

隱而不宣」還沒有工作。排除是否需要添加到forEach? – me9867

+0

options.forEach && exclusions.forEach? – me9867