[英]How to get div that fired event if i have function onclick on it?
給出以下HTML代碼:
<td role-id="@Model.Id">
@Model.Name
<div class='glyphicon glyphicon-edit update_user' onclick='UpdateRole()'></div>
</td>
單擊div時,我需要檢索role-id
。
JS代碼:
function UpdateRole() {
$("#ModalUser").show();
var role_id = $(this).parent().attr("role-id");
var user_id = $(this).parent().parent().attr("user-id");
console.log(role_id);
console.log(user_id);
};
這兩個值都是undefined
,沒有這個我怎么能得到role-id
?
更好的方法是使用jQuery
事件綁定,但是使用您的方法,從調用的函數傳遞this
上下文:
問題:在您的示例中, this
不是在其上調用事件的element
,而是window
!
function UpdateRole(that) {
$("#ModalUser").show();
var role_id = $(that).parent().attr("role-id");
var user_id = $(that).parent().parent().attr("user-id");
console.log(role_id);
console.log(user_id);
};
<td role-id="@Model.Id">
@Model.Name
<div class='glyphicon glyphicon-edit update_user' onclick='UpdateRole(this)'></div>
</td>
使用jQuery
event-binding
:
function UpdateRole() {
$("#ModalUser").show();
var role_id = $(this).parent().attr("role-id");
var user_id = $(this).parent().parent().attr("user-id");
console.log(role_id);
console.log(user_id);
}
$('.update_user').on('click', UpdateRole);
<td role-id="@Model.Id">
@Model.Name
<div class='glyphicon glyphicon-edit update_user' onclick='UpdateRole(this)'></div>
</td>
您應該使用jQuery注冊事件,這使查找調用元素變得更加容易:
$('.update_user').click(UpdateRole);
您現在可以:
function UpdateRole() {
var clickedElement = $(this);
$("#ModalUser").show();
var role_id = clickedElement.parent().attr("role-id");
var user_id = clickedElement.parent().parent().attr("user-id");
console.log(role_id);
console.log(user_id);
};
這非常簡單,您需要使用來更新此行。 data- *是html5用於設置和獲取數據的新屬性
$(".update_user").on("click",function(){
elm=$(this).parent().data("role-id");
elm // this element consist of role id, now you can use this variable
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.