2016-08-01 69 views
2

我想獲得我已經附加到我的HTML元素的ID屬性。但是,我得到的只是'未定義'。我該如何解決這個問題?jQuery的 - 不能獲取附加元素的屬性

jQuery('form#formular').append('<input id="upload_image_button" type="button" class="button" value="Upload" onclick="myFunction();" />'); 

function myFunction(){ 
    alert(jQuery(this).attr("id")); 
} 

回答

0
$('body').find('input[class="button"]').attr('id') 

或嘗試通過ID作爲函數的參數

...append('<input id="upload_image_button" type="button" class="button" value="Upload" onclick="myFunction(this.id);" />'); 

function myFunction(id){ 
alert(id) 
} 
0

你可以通過「這個」函數參數和函數定義,你會得到整個輸入標籤

jQuery('form#formular').append('<input id="upload_image_button" type="button" class="button" value="Upload" onclick="myFunction(this)" />'); 

function myFunction(e){ 
$(e).attr('id') 
} 
+0

'e'會發生事件,如果不使用它的屬性,您將無法獲得ID – brk

+0

我可能是錯的,但它每次都適用於我... –