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:08

just call "onclick"!

here's an example html:

<div id="c" onclick="alert('hello')">Click me!</div>
<div onclick="document.getElementById('c').onclick()">Fake click the previous link!</div>
查看更多
\"骚年 ilove
3楼-- · 2020-01-26 08:09

If you're using jQuery, you need to use the .trigger function, so it would be something like:

element.trigger('click');

http://api.jquery.com/trigger/

查看更多
Summer. ? 凉城
4楼-- · 2020-01-26 08:10

You can also try getting the element's onclick attribute and then passing into eval. This should work despite the big taboo over eval. I put a sample below

eval(document.getElementById('elementId').getAttribute('onclick'));
查看更多
Bombasti
5楼-- · 2020-01-26 08:12

This is a perfect example of where you should use a javascript library like Prototype or JQuery to abstract away the cross-browser differences.

查看更多
不美不萌又怎样
6楼-- · 2020-01-26 08:13
var clickEvent = new MouseEvent('click', {
  view: window,
  bubbles: true,
  cancelable: true
});
var element = document.getElementById('element-id'); 
var cancelled = !element.dispatchEvent(clickEvent);
if (cancelled) {
  // A handler called preventDefault.
  alert("cancelled");
} else {
  // None of the handlers called preventDefault.
  alert("not cancelled");
}

element.dispatchEvent is supported in all major browsers. The example above is based on an sample simulateClick() function on MDN.

查看更多
够拽才男人
7楼-- · 2020-01-26 08:15

I could be misinterpreting your question, but, yes, this is possible. The way that I would go about doing it is this:

var oElement = document.getElementById('elementId');   // get a reference to your element
oElement.onclick = clickHandler; // assign its click function a function reference

function clickHandler() {
    // this function will be called whenever the element is clicked
    // and can also be called from the context of other functions
}

Now, whenever this element is clicked, the code in clickHandler will execute. Similarly, you can execute the same code by calling the function from within the context of other functions (or even assign clickHandler to handle events triggered by other elements)>

查看更多
登录 后发表回答