When click my function, i want to change a parent that have this function element. But $(this) not working.
What is wrong?
function accountConfirm(message, title, yes_label, no_label, callback) {
console.log($(this));
$("#accountConfirmModal").attr('data-confirm-yes', false);
if ($("#accountConfirm").length == 0) {
.....
}
$("#accountConfirmModal .content p").html(message || "");
};
That is the HTML element
<button type="button" id="deleteScrollTop" class="btn btn-delete"
onclick="accountConfirm(jsResources.addressDeleteQuestion,jsResources.addressDeleteTitle, jsResources.yes,jsResources.no ,function(res){
if(res){
window.location.href = '@(Url.RouteUrl("CustomerAddressDelete", new {addressId = address.Id}))'
}
})">
<img src="@Url.ThemeFolderUrl("_images/delete.png")" alt="delete address" />
</button>
You possibly meant to do this
Always a good idea to consolidate on jQuery if you use it and not use inline event handlers
Assuming the button ID is unique
function accountConfirm(message, title, yes_label, no_label, callback) {
$("#accountConfirmModal").attr('data-confirm-yes', false);
if ($("#accountConfirm").length == 0) {
.....
}
$("#accountConfirmModal .content p").html(message || "");
};
const route = function(res) {
if (res) {
window.location.href = '@(Url.RouteUrl("CustomerAddressDelete", new {addressId = address.Id}))'
}
}
$("#deleteScrollTop").on("click", function() {
console.log($(this));
accountConfirm(jsResources.addressDeleteQuestion,
jsResources.addressDeleteTitle,
jsResources.yes,
jsResources.no, route)
})
<button type="button" id="deleteScrollTop" class="btn btn-delete">
<img src="@Url.ThemeFolderUrl("_images/delete.png")" alt="delete address" />
</button>
When you invoke a function in a onclick attribute, it is actually invoked by the window object, so this will become the window object itself, not the button.
If you want the this become the button itself, you will have to use apply method of the function.
For example:
function somefunc(arg1, arg2){
console.log("This is ", this);
console.log("Arg1: ", arg1);
console.log("Arg2: ", arg2);
}
In onclick
<button onclick="somefunc.apply(this, [1, 2])">Button</button>
If you want to access "this" in an onClick-event, you do it like this:
<button onclick="accountConfirm(this)">
your button
</button>
<script>
function accountConfirm(elmnt) {
console.log("this: ", elmnt);
};
</script>