2017-04-04 66 views
0

我有一個微小的腳本我工作:)運行JavaScript點擊

的想法是,如果跨度標籤只是包含autocompleteitemautocompleteitem autocompleteitemwithcontainer然後它會顯示單詞hello。現在它顯示hello兩種:(

演示:https://jsfiddle.net/L33mqqtp/

$(document).ready(function() { 
      $(document).on('click','.autocompleteitem',function(){ 
      $("div").show(); 
     }); 
    }); 

如何更新我的代碼要做到這一點

回答

3

試試這個

'click','.autocompleteitem:not(.autocompleteitemwithcontainer)' 
+0

哇 - 驚人。謝謝,Ilya :-) – michaelmcgurk

1

他們倆?有.autocompleteitem類!要獲得您想要的,請使用不同的選擇器,該選擇器僅適用於第一個:

$(document).ready(function() { 
    $(document).on('click','.autocompleteitem:not(".autocompleteitemwithcontainer")',function(){ 
    $("div").show(); 
    }); 
}); 
1

試試這個

$(document).ready(function() { 
    $("span").on('click', function(){ 
     if(this.className == "autocompleteitem") 
      $("div").show(); 
    }); 
}); 
1

使用屬性選擇器語法。這將允許您直接匹配整個屬性。這樣你就不必爲每一件你不想被選中的東西做一堆不同的組合。

實施例的選擇器:jQuery('[class="autocompleteitem"]')

工作實施例:

$(document).ready(function() { 
 
      $(document).on('click','[class="autocompleteitem"]',function(){ 
 
      $("div.containertoshow").toggle(); 
 
     }); 
 
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<a href="#" class="autocompleteitem">Should work</a><br> 
 
<a href="#"class="autocompleteitem autocompleteitemwithcontainer">Should not work</a> 
 

 
<div class="containertoshow" style="display:none;">That button does toggle me on/off!</div>

相關問題