Fake “click” to activate an onclick method

前端 未结 11 696
醉话见心
醉话见心 2020-11-28 10:11

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.

I

相关标签:
11条回答
  • 2020-11-28 10:41

    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">

    0 讨论(0)
  • 2020-11-28 10:42

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

    0 讨论(0)
  • 2020-11-28 10:44

    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)>

    0 讨论(0)
  • 2020-11-28 10:44

    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/

    0 讨论(0)
  • 2020-11-28 10:46

    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'));
    
    0 讨论(0)
  • 2020-11-28 10:47

    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>
    
    0 讨论(0)
提交回复
热议问题