How To Get Div That Fired Event If I Have Function Onclick On It?
Given this HTML code: @Model.Name I
Solution 1:
Better approach is to use jQuery
event binding, but using your approach, pass this
context from called function:
Problem: In your example, this
is not the element
on which event is invoked but window
!
functionUpdateRole(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);
};
<tdrole-id="@Model.Id">
@Model.Name
<divclass='glyphicon glyphicon-edit update_user'onclick='UpdateRole(this)'></div></td>
Using jQuery
event-binding
:
functionUpdateRole() {
$("#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);
<tdrole-id="@Model.Id">
@Model.Name
<divclass='glyphicon glyphicon-edit update_user'onclick='UpdateRole(this)'></div></td>
Solution 2:
You should register your event using jQuery, this makes it much easier to find the calling element:
$('.update_user').click(UpdateRole);
You can now:
functionUpdateRole() {
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);
};
Solution 3:
this is very simple you need to update this line with . data-* is html5 new attribute for setting and getting data
$(".update_user").on("click",function(){
elm=$(this).parent().data("role-id");
elm // this element consist of role id, now you can use this variable
});
Post a Comment for "How To Get Div That Fired Event If I Have Function Onclick On It?"