How to pass the button value into my onclick event function?

后端 未结 5 2032
失恋的感觉
失恋的感觉 2020-12-24 13:12
test

The dosomething function evoked when to click the button,how can pa

相关标签:
5条回答
  • 2020-12-24 13:47

    You can pass the value to the function using this.value, where this points to the button

    <input type="button" value="mybutton1" onclick="dosomething(this.value)">
    

    And then access that value in the function

    function dosomething(val){
      console.log(val);
    }
    
    0 讨论(0)
  • 2020-12-24 13:54

    You can pass the element into the function <input type="button" value="mybutton1" onclick="dosomething(this)">test by passing this. Then in the function you can access the value like this:

    function dosomething(element) {
      console.log(element.value);
    }
    
    0 讨论(0)
  • 2020-12-24 13:55

    You can do like this.

    <input type="button" value="mybutton1" onclick="dosomething(this)">
    
    function dosomething(element){
        alert("value is "+element.value); //you can print any value like id,class,value,innerHTML etc.
    };
    
    0 讨论(0)
  • 2020-12-24 13:59

    Maybe you can take a look at closure in JavaScript. Here is a working solution:

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8" />
            <title>Test</title>
        </head>
        <body>
            <p class="button">Button 0</p>
            <p class="button">Button 1</p>
            <p class="button">Button 2</p>
            <script>
                var buttons = document.getElementsByClassName('button');
                for (var i=0 ; i < buttons.length ; i++){
                  (function(index){
                    buttons[index].onclick = function(){
                      alert("I am button " + index);
                    };
                  })(i)
                }
            </script>
        </body>
    </html>

    0 讨论(0)
  • 2020-12-24 14:06

    You can get value by using id for that element in onclick function

    function dosomething(){
         var buttonValue = document.getElementById('buttonId').value;
    }
    
    0 讨论(0)
提交回复
热议问题