Fake “click” to activate an onclick method

2020-01-26 07:36发布

I have an element with an onclick method.

I would like to activate that method (or: fake a click on this element) within another function.

Is this possible?

11条回答
霸刀☆藐视天下
2楼-- · 2020-01-26 08:16

I haven't used jQuery, but IIRC, the first method mentioned doesn't trigger the onclick handler.

I'd call the associated onclick method directly, if you're not using the event details.

查看更多
男人必须洒脱
3楼-- · 2020-01-26 08:28

If you're using JQuery you can do:

$('#elementid').click();
查看更多
迷人小祖宗
4楼-- · 2020-01-26 08:28

Once you have selected an element you can call click()

document.getElementById('link').click();

see: https://developer.mozilla.org/En/DOM/Element.click

I don't remember if this works on IE, but it should. I don't have a windows machine nearby.

查看更多
兄弟一词,经得起流年.
5楼-- · 2020-01-26 08:31

Using javascript you can trigger click() and focus() like below example

document.addEventListener("click", function(e) {
  console.log("Clicked On : ",e.toElement);
},true);
document.addEventListener('focus',function(e){
  console.log("Focused On : ",e.srcElement);
},true);

document.querySelector("#button_1").click();
document.querySelector("#input_1").focus();
<input type="button" value="test-button" id="button_1">
<input type="text" value="value 1" id="input_1">
<input type="text" value="value 2" id="input_2">

查看更多
霸刀☆藐视天下
6楼-- · 2020-01-26 08:32

For IE there is fireEvent() method. Don't know if that works for other browsers.

查看更多
登录 后发表回答