-1

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?

asko1
  • 3
  • 3

2 Answers2

0

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)" />
Unmitigated
  • 46,070
  • 7
  • 44
  • 60
0

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)
}
Kinglish
  • 21,356
  • 3
  • 21
  • 41