Suppose I have an anchor in my page like :<a href="#header" id="anchor">turn to header</a> then I also set a button in my page <input type="button" value="triger anchor"> .What I want to do is that ,when I click the button ,it will triger the anchor's default click event ,as the page turn to "header".So I write $("input").click(function(){$("#anchor").trigger("click");}); But it seems doesn't work .So how can I achieve that?Thank you
Add a comment
|
5 Answers
Please see this answer.
Instead of trying to trigger the click event, try setting the window.location property:
window.location = '#header';
Or perhaps:
$("input").click(function() {
window.location = $('#anchor').attr('href');
});
1 Comment
Peter Ajtai
Note that this will not send the referer for IE6, IE7 and I think IE8.
jQuery does not have a way to trigger the native DOM event directly.
To do that, you can use the plain old standard DOM methods:
var evt = document.createEvent("Event");
evt.initEvent("click", true, true);
$('#anchor').get(0).dispatchEvent(evt);
For support of IE8 or earlier, you need to use the IE-specific event methods createEventObject and fireEvent.
Comments
You have a spelling error. Please use:
{$("#anchor").trigger("click");});
4 Comments
hh54188
……I'm sorry ,it just a write mistake .In my project it is"trigger",and doesn;t work……
Andrei Andrushkevich
ok, try to add $("#anchor").bind('click', function(){alert('click')}); it is help you to check that event is happend
Andrei Andrushkevich
also add attrib. id for button and use it in your jQuery's query
Andrei Andrushkevich
all this help you to find the reason of problem.