我檢查了一些被問到的類似問題。如何在jQuery中單擊時獲取按鈕的ID?
我想添加/刪除按鈕,當用戶動態地點擊添加/刪除按鈕。因此,每個按鈕都必須有一個唯一的ID來標識自己。
下面是HTML代碼的一部分:
<p id="q1">Question: 1<input type="text" class="ttt"/>
<button class="buttonPlus" type="button"></button>
<button class="buttonMinus" type="button" id="1"></button></p>
這裏是jQuery代碼的一部分:除了上述方法
var questionCount = 1;
$("#q1").append("<p id='p2'>Question: " + ++questionCount + "<input type='text'>\
<button type='button' class='buttonPlus'></button>\
<button type='button' class='buttonMinus' id=questionCount></button></p>");
//Re-binding
var newBtnPlus = $("#q1").find('.buttonPlus:last');
var newBtnMinus = $("#q1").find('.buttonMinus:last');
newBtnPlus.click(function(){
btnPlsClickEvent(newBtnPlus);
});
newBtnMinus.click(function() {
btnMnsClickEvent(newBtnMinus);
});
function btnMnsClickEvent(btn) {
var idNum = $(this).attr("id");
alert(idNum);}
,我曾嘗試: ALTER(this.id) ; alter(btn.id); .etc。
我不知道爲什麼我不能得到我已動態分配給減號按鈕的id,也不能獲得由html完成的靜態分配的id。
我一直堅持這個問題幾個小時。 你能幫我嗎?
感謝, 阿什利
我假設你將減號/加號事件綁定到多個元素,因此需要分隔「btnMnsClickEven」fu nctions? –
你期望得到什麼回報?一些注意事項:使用以數字開頭的ID在語義上是非法的。此外,當您通過javascript創建元素時,您設置的ID缺少引號。 – kroehre