2015-02-10 155 views
-4

如果我的按鈕是如下如果在jQuery中使用多個具有相同ID的按鈕,如何檢測哪個按鈕被點擊?使用ID,而不是

<input type="button" id="btnOrderLiterature" value="<%=submitButtonText %>" ng-click="addLiteratureToSession($event)" /> 

現在還有用相同的ID很多按鈕的頁面上,如果我要檢測被點擊的按鈕,並改變其值,那麼怎麼可以管理它?

+6

_there是許多按鈕在頁面上具有相同的ID。我停在這裏。 – melancia 2015-02-10 14:15:20

+1

我知道它不是你想聽到的,但ID只用於單個元素的選擇。課程旨在滿足您在滿足所需功能的同時滿足您的需求。 – 2015-02-10 14:15:56

+4

** ID應該是唯一的**。如果人們共享身份證,你會如何識別他們?問問你自己這個問題。 – melancia 2015-02-10 14:16:20

回答

0

看看這個簡單的例子,而不是使用類。我更改了按鈕的值/文字以更好地說明該示例。

//your selector here is any btnOrderLiterature class 
 
$(".btnOrderLiterature").click(function() 
 
{ 
 
    //Here you handle what happens when 
 
    //the user clicks an element that holds the btnOrderLiterature class 
 
    alert($(this).val()); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type="button" class="btnOrderLiterature" value="1" ng-click="addLiteratureToSession($event)" /> 
 
<input type="button" class="btnOrderLiterature" value="2" ng-click="addLiteratureToSession($event)" /> 
 
<input type="button" class="btnOrderLiterature" value="3" ng-click="addLiteratureToSession($event)" /> 
 
<input type="button" class="btnOrderLiterature" value="4" ng-click="addLiteratureToSession($event)" /> 
 
<input type="button" class="btnOrderLiterature" value="5" ng-click="addLiteratureToSession($event)" />

0

您的ID必須是唯一的,但類可以是一樣的。因此,爲所有具有相同類名的元素添加點擊監聽器

<input type="button" id="1" value="1" class="btn"/> 
<input type="button" id="2" value="2" class="btn"/> 
<input type="button" id="3" value="3" class="btn"/> 


$(function() { 
    $(".btn").on('click', function (e) { 
     alert($(this).val()); 
    }); 
}); 
+0

你的代碼不起作用。 http://jsfiddle.net/MelanciaUK/2h02svwh/1/ – melancia 2015-02-10 14:22:54

+0

你嘗試委派是不正確的。 – melancia 2015-02-10 14:24:07

+1

我想這就是你在想什麼:http://jsfiddle.net/MelanciaUK/2h02svwh/2/ – melancia 2015-02-10 14:26:57

0

因此,對於有效的HTML,ID必須在其範圍內唯一。 請看這裏:w3c specification

所以,如果你不想改變你的HTML標記,你可以用另外一種選擇,如:

$('input[type=button]').on('click', function(){ 
    $(this).val('new value'); // $(this) is refering to the actual clicked button 
}); 

參考

attribute selector

相關問題