2014-09-27 159 views
3

因此,我一直在撓頭,以獲取點擊按鈕的ID,但是無法正確理解。它始終返回我undefined獲取被點擊的按鈕的ID

這裏的小提琴:http://jsfiddle.net/thinkinbee/mx0rb5cy/

有沒有,我還沒有列入我的小提琴的東西嗎? 。我的JS代碼有問題嗎?

我參考了以前的問題,但似乎沒有任何工作。我試圖實施$(this).attr("id")this.id,但沒有任何積極的結果。

也在更長的時間去我的所有按鈕將動態。任何東西額外我將需要處理呢?

回答

6

如果按鈕是動態的,您應該使用document.on。

我收到了你撥弄着這樣工作:http://jsfiddle.net/1ehy66k9/

$(document).on('click', '.ui-btn', function() { 
    alert("Clicked with Id "+$(this).attr('id')); 
}); 
+0

作品完美@Jim感謝,但只是第二次思想此功能會將我的所有按鈕都歸還給我?有沒有其他的只能從一個特定的div獲得按鈕(原諒我在jquery和JS上不好,我剛開始弄髒我的手) – thinkinbee 2014-09-27 13:24:49

+0

我對選擇器也不是很好。像這樣? http://jsfiddle.net/92400whm/ – 2014-09-27 13:31:06

1

試試這個 -

HTML -

<a class="ui-btn ui-btn-inline ui-mini" id="check" onclick="chkAlert(this)">click me</a> 

的JavaScript -

var chkAlert = function(t){ 
    alert("Clicked with Id "+$(t).attr('id')); 

}; 

http://jsfiddle.net/mx0rb5cy/6/

1

你需要發送按鈕進入功能變量this

<a class="ui-btn ui-btn-inline ui-mini" id="check" onclick="chkAlert(this)">click me</a> 

,然後接受它裏面的功能(你可以命名爲任何你想要的功能裏面)

var chkAlert = function(caller){ 
    alert("Clicked with Id "+caller.id); 
}; 

Example

2

你應該通過this作爲參數:

<a class="ui-btn ui-btn-inline ui-mini" id="check" onclick="chkAlert(this)">click me</a> 
var chkAlert = function(elem){ 
    alert("Clicked with Id "+$(elem).attr('id')); 
    alert("Clicked with Id "+elem.id); 
}; 

JSFiddle Demo

1

你可以通過ID像的onclick =「chkAlert(this.id)」功能,請嘗試如圖

<a class="ui-btn ui-btn-inline ui-mini" id="check" onclick="chkAlert(this.id)">click me</a> 


var chkAlert = function(id){ 
    alert("Clicked with Id "+id); 
    alert("Clicked with Id "+id); 
};