I have this simple code : here
$(".btn").on('click',function () {
$(".a").trigger('click');
});
$(".btn2").on('click',function () {
$(".a")[0].click();
});
I'm trying to simulate pressing on Anchor.
But when I use jQuery's trigger
, it doesn't work (why?)
When I use "jsobj".click()
func, it does work.
After reading the jQuery documentation, I don't see any reason why it shouldn't.
Help ?
PS: I'm using Chrome.
So, using a string that is tied to a function, onclick produces an attribute within the binded HTML tag. . click, on the other hand, attaches the function to the property element.
jQuery trigger() Method The trigger() method triggers the specified event and the default behavior of an event (like form submission) for the selected elements. This method is similar to the triggerHandler() method, except that triggerHandler() does not trigger the default behavior of the event.
trigger( "click" ); As of jQuery 1.3, . trigger() ed events bubble up the DOM tree; an event handler can stop the bubbling by returning false from the handler or calling the . stopPropagation() method on the event object passed into the event.
click is a function on HTML elements you can call to trigger their click handlers: element. click(); onclick is a property that reflects the onclick attribute and allows you to attach a "DOM0" handler to the element for when clicks occur: element.
Actually $(".a").trigger('click');
triggers the click event but it doesn't mean that it'll click the link, instead it'll execute the event handler if you already have one, i.e.
$(".btn, .btn2").on('click',function () {
$($(".a")[0]).trigger('click'); // first element
});
$(".a").on('click', function (e){
alert(e.target);
});
The given example will trigger the click event of the a
and will execute the handler (the anonymous function) that's already have been registered for that event using
$(".a").on('click', function (e){...});
DEMO.
because $(".a")[0]
return raw JavaScript node you cannot use jQuery object methods for that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With