2015-03-19 69 views
-2

我有這樣Javascript或jQuery的獲得事件的任何按鈕單擊

<button>Button One</button> 
<button>Button Two</button> 
<button>Button Three</button> 
<input type="Text" value="Content Text"> 
<a href="somewhere.php">URL</a> 

我需要獲取事件,如果任何按鈕,點擊

我一直在嘗試使用HTML代碼:

$(":button").click(function() { 
    alert("button click"); 
}); 

感謝幫助

+0

你嘗試過什麼應該有工作,你可以提供一個[MCVE](/幫助/ MCVE)? – 2015-03-19 08:16:07

+0

備註:請注意,如果這些按鈕處於表單中,則會提交。 (令人驚訝的)'button'元素的默認''類型''是''submit'''。 – 2015-03-19 08:16:24

+0

大多數你將不得不使用文檔準備處理程序 – 2015-03-19 08:17:59

回答

3

你有什麼會努力感謝提供按鈕的存在,當你運行你的代碼jQuery的定製:button選擇。爲了讓他們能夠存在,或者:

  1. 您必須在script元素是在HTML(之前收盤</body>標籤是最好的)按鈕的代碼,或

  2. 您必須使用jQuery的ready回調等到元素已創建

  3. 您必須推遲執行該代碼的另一種方式,如windowload callbac K,但是這非常下旬在頁面加載過程

注意,使用jQuery的自定義CSS選擇器可能不理想,你可能想改變$(":button")$("button")$("button, input[type=button]")讓jQuery的可以將它交給瀏覽器的內置CSS選擇器引擎。

的#1示例:

<button>Button One</button> 
 
<button>Button Two</button> 
 
<button>Button Three</button> 
 
<input type="Text" value="Content Text"> 
 
<a href="somewhere.php">URL</a> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<script> 
 
$(":button").click(function() { 
 
    alert("button click"); 
 
}); 
 
</script>

的#2示例:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<script> 
 
$(function() { // Or: `$(document).ready(function() {`, they're the same 
 
    $(":button").click(function() { 
 
    alert("button click"); 
 
    }); 
 
}); 
 
</script> 
 
<button>Button One</button> 
 
<button>Button Two</button> 
 
<button>Button Three</button> 
 
<input type="Text" value="Content Text"> 
 
<a href="somewhere.php">URL</a>

+0

對不起,我週末與我的家人,是的有用,我的錯誤是代碼不是我放在$(document).ready(function()。謝謝你的答案(y) – Artron 2015-03-22 16:44:37

1

試試這個:刪除:。這是標籤選擇器,它沒有.,沒有:或沒有#,但只是標籤名稱。在jQuery Selectors

+0

什麼是http://api.jquery.com/button-selector/ – 2015-03-19 08:14:41

+0

是的,我更新了我的答案。謝謝@ArunPJohny – 2015-03-19 08:15:54

+0

所以你的答案是使用'button'選擇器,即使':button'工作。這不會有用。 :-) – 2015-03-19 08:17:03

0

$("button").click(function() { 
    alert("button click"); 
}); 

更多信息,只需從.click事件刪除:

有對你是一個小提琴:http://jsfiddle.net/u1q6obLz/

瞭解更多關於jQuery選擇HERE

+0

實際上,jQuery提供了[':button' selector](http://api.jquery.com/button-selector/)。 OP的代碼應該可以工作。 – 2015-03-19 08:17:24