I am trying to append an event to a link's click handler. I can select the element by its href
element, but when I enter the following code into the Javascript console, the event is triggered, rather than having an event handler added:
$('a[href="example.com"]')[0].click(console.log("Message"))
I've read through the docs for .click() , which state that calling .click
with an argument shouldn't trigger the event, and am not sure why this is happening.
You are trying to call .click()
of HTMLELement
which doesn't exist.
When you do [some number]
on jQuery
object, the corresponding HTMLElement
will be returned. But .click()
is a function of jQuery
and not of HTMLElement
. Also you should wrap your code in an anonymous function.
Do this:
$('a[href="example.com"]').click(function(){
console.log("Message")
});
Using HTMLELement, you would do this:
$('a[href="example.com"]')[0].onclick = function(){
console.log("Message")
}
But I don't recommend the above approach. Just saying that the above exists too.
You forget to write the function, you need to wrap code in function. Try this,
$('a[href="example.com"]').click(function(){console.log("Message")})
Click is an event of jQuery so when you select element by $ it returns jquery object and you can call further jquery event on that object. but when you write [0]
it returns DOM element and that has no click event handler.
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.