You could use Function#call
, but it is generally better to use addEventListener
.
function deleteTask() {
console.log(this)
}
<input type="button" value="Delete Task" onclick="deleteTask.call(this)" />
You could use Function#call
, but it is generally better to use addEventListener
.
function deleteTask() {
console.log(this)
}
<input type="button" value="Delete Task" onclick="deleteTask.call(this)" />
In jQuery you’d set it up like this:
html:
<input type="button" value="Delete Task" data-role='delete' />
script:
$(document).ready(function() {
$('[data-role=delete]').click( deleteTask )
})
function deleteTask() {
// element clicked is this -- or if you want it ready for JQ: $(this)
}
I have a function called deleteTask which currently just does console.log(this)
<input type="button" value="Delete Task" onclick="deleteTask()"/>
(note that this in a jQuery function, not in a HTML file) returns [object Window]
while del.onclick = deleteTask;
(where del is the input button) returns the object that was clicked, in this case, <input>
How can I have the jQuery version output similarly to the pure JS one?
What does that have to do with jQuery?
I may have been wrong to flag this as jQuery, but the
Thank you, this worked perfectly! If I may ask, what makes using addEventListener better?
@asko1 Happy to help. Take a look at this answer:
The actual element is