2017-10-07 150 views
0

我想要訪問按鈕的ID,當我寫入PHP變量javascript代碼創建錯誤「未定義」的值。如何使用javascript onclick()獲取元素的屬性值?

function update_profile(){ $(function() { 
var element = $(this); 
var update_id = element.attr("id"); 
    var infoo = 'updated_id=' + update_id; 

    document.getElementsByClassName('test')[0].innerHTML=infoo; 


}); 
} 

按鈕代碼:

<button data-toggle="modal" data-target=".bs-example-modal-lg" onclick="update_profile()" class="btn-xs btn-warning " id='<?php echo $user_rec[1]; ?>' >Update</button> 
+0

首先,我不認爲你需要用'$(函數(){'和關閉它'});' – Walk

+0

刪除'$(函數(){})'並改變'document.getElementsByClassName('test')[0] .innerHTML = infoo;'到'$(「。test」)。first()。html(infoo);'或者更好:'$(function(){ $(「。btn-warning」)。on(「click」,function(){$(「。test」)。first()。html(this.id);});});' – mplungjan

回答

1

你不需要$(function() { });你的函數內。您必須將this傳遞給您的函數,以便知道哪個元素被點擊。

function update_profile(element){ 
 
    var update_id = element.id; 
 
    var infoo = 'updated_id=' + update_id; 
 
    document.getElementsByClassName('test')[0].innerHTML = infoo; 
 
}
<div class="test">test class element</div> 
 
<button data-toggle="modal" data-target=".bs-example-modal-lg" onclick="update_profile(this)" class="btn-xs btn-warning " id='idName' >Update</button>