How do I send a click event (JS or JQuery) to a parent object that is an anchor? My basic HTML looks like:
<a href="javascript:myFunc(1,2,3)">
<img id="b开发者_StackOverflow中文版tn1" src="myimg.png">
</a>
So I can easily reference the anchor through button via:
document.getElementById('btn1').parentNode
However,
document.getElementById('btn1').parentNode.click
while it doesn't seem to raise an error in the console on firebug, the javascript function doesn't seem to be firing either. How do I send a click to this thing. By the way, I don't have control of the HTML so I can't just ad an ID to the anchor tag.
Gone are the days when it's okay to use the href="javascript:blah"
, especially if you're using a library like jQuery, Dojo, ExtJs or the rest. Event handlers should always be attached outside of the HTML.
$(function() {
$("#btn1").click(function() {
$(this).parent().click();
};
});
Here is a snippet that you can test on SO pages (copy+paste into Firebug)
$("#hlogo a").click(function() {
alert("a!");
return false;
});
$("#hlogo a img").click(function() {
alert("img!");
$(this).parent().click();
});
Normal Links with Normal HREF's
// assuming the link is always the immediate parent of #btn1
$("#btn1").parent().trigger("click");
Links with Javascript-Commands as HREF's
I note in your case though that your HREF value is a call to a javascript function, with parameters. For this, you may want to evaluate that HREF, rather than click the link:
// run the href-javascript from the parent anchor
eval($("#btn1").parent().attr("href"));
I've built a test-case and used firebug to try both methods. The first returns 1
, showing the link was clicked, but the javascript is never executed. The second method actually executes the javascript found within the HREF value of the link itself. This should be an adequate solution to your specific need.
EDIT: ignore this answer as it's no good for links; see the comments below.
The click
property of an a
element is a function property, aka a method; all you are doing is referencing the property, not invoking it.
document.getElementById('btn1').parentNode.click();
(note the ()
to cause the method to be invoked) should do it, though if you are using jQuery already then Jonathan Sampson's answer will do what you need - there's no point in loading the library and then not using it :-)
Although Jonathan's answer can be shortened, as jQuery provides a click
method:
$("#btn1").parent().click();
jQuery way maybe like this:
$(event.target).closest('a').trigger('click')
or in your words something like this
$('#bth1').closest('a').trigger('click')
精彩评论