2016-11-25 55 views
3

所以,我有一個問題。在我的其中一個項目中,我想爲面板添加一個slideToggle函數,點擊標題。我基本上想要這個。Jquery .click()不適用於標題

https://jsfiddle.net/abrch86f/

的問題是,當我點擊標題,(一個H3),沒有任何反應,並檢查,我說的點擊功能的警報消息也是如此。我基本上都在尋找會導致這種情況發生的常見錯誤。 JQuery被definetely加載,我總是使用文檔加載的警報消息來檢查。這裏是我的代碼

JQuery的

$('h3').click(function(){ 
    alert("It works!"); 
    $('.content').slideToggle(); 
}); 

HTML

<div id="left-panel"> 
<h3>Hire Soldiers</h3> 

      <div class="content"> 
      <button onClick="hireSwordsman()">Swordsman - Cost 70 Ore</button> 
      <button onClick="hireVanguard()">Vanguard - Cost 90 Ore</button> 
      <button onClick="hireBowman()">Bowman - Cost 125 Ore</button> 
      <button onClick="hireKnight()">Knight - Cost 200 Ore</button> 
      </div> 
     </div> 

我包括我的左側面板DIV的原因是因爲我不知道,如果z-index的有什麼關係,但我有一種預感。可以顯示是一個問題?我不知道爲什麼會這樣,因爲我根本沒有改變它。我再次強調,我只是在尋找會導致它無法工作的事情。如果你認爲你可以直接幫助我,並需要更多信息,那就問。

謝謝!

+0

z-index肯定會導致這種情況發生。如果某些其他元素覆蓋了您想要點擊的「h3」元素,覆蓋'h3「的元素將會註冊點擊事件。 如果你在這個問題中用你的HTML代替了HTML中的HTML,並將'$ .slideToggle()'選擇器更改爲'.content',它應該可以很好地工作。 – josephting

+0

順便說一句,當遇到這些問題時,檢查實際上被點擊的一種好方法是在'ready()'後面執行此操作:$(document).click(function(e){ \t console.log(e.target); \t});' 但是,這會記錄您點擊的所有內容,因此將其註釋掉或在不需要時將其刪除。 – junkfoodjunkie

+0

哇@junkfoodjunkie這實際上是超級有用的!現在我可以確定有什麼東西擋住了我的h3。謝謝! –

回答

0

我的問題是,我H3我靶向單擊,被另一格掩蓋。感謝由@josephting我需要調整我的z-index是這樣高的解釋:

h3 { 
    z-index: 2; 
} 

一個很好的方法來檢查,如果你的元素被別的東西阻擋通過使用該功能通過@junkfoodjunkie解釋打印到控制檯日誌您點擊了什麼元素。

$(document).click(function(e){ console.log(e.target); }); 

因此,通過將該聲明添加到我的CSS,我的問題得到了解決。請記住,如果您以前使用過較高的z-index值,則可能需要根據您的標題前面的內容來提高它們。

0

我認爲這是你需要的。請讓我知道這是否適合你。

$(document).ready(function(){ 
 
$('h3').click(function(){ 
 
    $('.content').slideToggle(); 
 
}); 
 
});
.content{ 
 
display:none; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 
 
<div id="left-panel"> 
 
<h3>Hire Soldiers</h3> 
 

 
      <div class="content"> 
 
      <button onClick="hireSwordsman()">Swordsman - Cost 70 Ore</button> 
 
      <button onClick="hireVanguard()">Vanguard - Cost 90 Ore</button> 
 
      <button onClick="hireBowman()">Bowman - Cost 125 Ore</button> 
 
      <button onClick="hireKnight()">Knight - Cost 200 Ore</button> 
 
      </div> 
 
     </div>

+0

這不會解決我的問題,因爲我的h3被掩蓋了,儘管使用document.ready()是一個好主意。謝謝! –

+0

在感恩節這個季節分享一點愛,它不會公開露面,因爲我還沒有15個代表 –

相關問題