Change onclick action with a Javascript function

前端 未结 8 1372
刺人心
刺人心 2020-12-02 12:14

I have a button:


When I click this button the first time, I want it to exe

相关标签:
8条回答
  • 2020-12-02 12:29

    I recommend this approach:

    Instead of having two click handlers, have only one function with a if-else statement. Let the state of the BUTTON element determine which branch of the if-else statement gets executed:

    HTML:

    <button id="a" onclick="toggleError(this)">Button A</button>
    

    JavaScript:

    function toggleError(button) { 
        if ( button.className === 'visible' ) {
            // HIDE ERROR
            button.className = '';
        } else {
            // SHOW ERROR
            button.className = 'visible';
        }
    }
    

    Live demo: http://jsfiddle.net/simevidas/hPQP9/

    0 讨论(0)
  • 2020-12-02 12:36
    var Foo = function(){
        document.getElementById( "a" ).setAttribute( "onClick", "javascript: Boo();" );
    }
    
    var Boo = function(){
        alert("test");
    }
    
    0 讨论(0)
  • 2020-12-02 12:37

    Thanks to João Paulo Oliveira, this was my solution which includes a variable (which was my goal).

    document.getElementById( "myID" ).setAttribute( "onClick", "myFunction("+VALUE+");" );
    
    0 讨论(0)
  • 2020-12-02 12:38

    For anyone, like me, trying to set a query string on the action and wondering why it's not working-

    You cannot set a query string for a GET form submission, but I have found you can for a POST.

    For a GET submission you must set the values in hidden inputs e.g.

    an action of: "/handleformsubmission?foo=bar" would have be added as the hidden field like: <input type="hidden" name="foo" value="bar" />

    This can be done add dynamically in JavaScript as (where clickedButton is the submitted button that was clicked:

    var form = clickedButton.form;
    var hidden = document.createElement("input");
    hidden.setAttribute("type", "hidden");
    hidden.setAttribute("name", "foo");
    hidden.setAttribute("value", "bar");
    form.appendChild(hidden);
    

    See this question for more info submitting a GET form with query string params and hidden params disappear

    0 讨论(0)
  • 2020-12-02 12:40

    Your code is calling the function and assigning the return value to onClick, also it should be 'onclick'. This is how it should look.

    document.getElementById("a").onclick = Bar;
    

    Looking at your other code you probably want to do something like this:

    document.getElementById(id+"Button").onclick = function() { HideError(id); }
    
    0 讨论(0)
  • 2020-12-02 12:41

    Do not invoke the method when assigning the new onclick handler.

    Simply remove the parenthesis:

    document.getElementById("a").onclick = Foo;
    

    UPDATE (due to new information):

    document.getElementById("a").onclick = function () { Foo(param); };
    
    0 讨论(0)
提交回复
热议问题