简体   繁体   中英

How can I have a jQuery onclick function return the element instead of the event?

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?

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)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM