Change onClick attribute with javascript

后端 未结 6 1051
执笔经年
执笔经年 2020-12-02 16:35

This is my function and it should change the onClick attribute of the HTML input, but if I use

document.getElementById(\'buttonLED\'+id).onclick = \"writeLED         


        
相关标签:
6条回答
  • 2020-12-02 17:16

    The line onclick = writeLED(1,1) means that you want to immediately execute the function writeLED(arg1, arg2) with arguments 1, 1 and assign the return value; you need to instead create a function that will execute with those arguments and assign that. The topmost answer gave one example - another is to use the bind() function like so:

        var writeLEDWithSpecifiedArguments = writeLED.bind(this, 1,1);
        document.getElementById('buttonLED'+id).onclick = writeLEDWithSpecifiedArguments;
    
    0 讨论(0)
  • 2020-12-02 17:29

    You are not actually changing the function.

    onClick is assigned to a function (Which is a reference to something, a function pointer in this case). The values passed to it don't matter and cannot be utilised in any manner.

    Another problem is your variable color seems out of nowhere.

    Ideally, inside the function you should put this logic and let it figure out what to write. (on/off etc etc)

    0 讨论(0)
  • 2020-12-02 17:31

    You want to do this - set a function that will be executed to respond to the onclick event:

    document.getElementById('buttonLED'+id).onclick = function(){ writeLED(1,1); } ;
    

    The things you are doing don't work because:

    1. The onclick event handler expects to have a function, here you are assigning a string

      document.getElementById('buttonLED'+id).onclick = "writeLED(1,1)";
      
    2. In this, you are assigning as the onclick event handler the result of executing the writeLED(1,1) function:

      document.getElementById('buttonLED'+id).onclick = writeLED(1,1);
      
    0 讨论(0)
  • 2020-12-02 17:31

    Another solution is to set the 'onclick' attribute to a function that returns your writeLED function.

    document.getElementById('buttonLED'+id).onclick = function(){ return writeLED(1,1)};
    

    This can also be useful for other cases when you create an element in JavaScript while it has not yet been drawn in the browser.

    0 讨论(0)
  • 2020-12-02 17:34

    Using Jquery instead of Javascript, use 'attr' property instead of 'setAttribute'

    like

    $('buttonLED'+id).attr('onclick','writeLED(1,1)')
    
    0 讨论(0)
  • 2020-12-02 17:38

    Well, just do this and your problem is solved :

    document.getElementById('buttonLED'+id).setAttribute('onclick','writeLED(1,1)')
    

    Have a nice day XD

    0 讨论(0)
提交回复
热议问题