I am trying to bind two elements on a Web page, so that when I click on开发者_Python百科 one, it also triggers the click on the other. For example I have data presented in both a table and a pie chart, and clicking on the chart should have the same effect as clicking directly on the data in the table.
[Edit] I need it as a generic utility, as I don't necessarily know what action the original element will trigger.
How can I achieve this, cross-browser, in plain JavaScript?
What I am looking for has some similarities with the jQuery click()
method, except that:
- I am not using jQuery
- I don't need to trigger the click programmatically, the user will do it
It is also similar to the JavaScript click()
, but click()
doesn't work cross-browser.
Updated code. This should do it. When you click the second element, call the first element's click event and pass in the first button as this
<div onclick="alert(this.getAttribute('id'));" id="b1" >Hi!!</div>
<div id="b2" >Hi!! 2</div>
With this code:
document.getElementById("b2").onclick = function() {
document.getElementById("b1").onclick.call(document.getElementById("b1"));
};
Also in this fiddle: http://jsfiddle.net/RVAMm/26/
Why not use:
theElementYouWantToClick.onClick()
精彩评论