Passing string parameter in JavaScript function

后端 未结 6 1484
夕颜
夕颜 2021-02-04 10:27

I was trying to pass a string to a JavaScript function.

As it\'s mentioned here - Pass a string parameter in an onclick function

I\'m using this simple co

相关标签:
6条回答
  • 2021-02-04 11:00

    Use this:

    document.write('<td width="74"><button id="button" type="button" onclick="myfunction('" + name + "')">click</button></td>')
    
    0 讨论(0)
  • 2021-02-04 11:01
    document.write(`<td width='74'><button id='button' type='button' onclick='myfunction(\``+ name + `\`)'>click</button></td>`)
    

    Better to use `` than "". This is a more dynamic answer.

    0 讨论(0)
  • 2021-02-04 11:10

    The question has been answered, but for your future coding reference you might like to consider this.

    In your HTML, add the name as an attribute to the button and remove the onclick reference.

    <button id="button" data-name="Mathew" type="button">click</button>
    

    In your JavaScript, grab the button using its ID, assign the function to the button's click event, and use the function to display the button's data-name attribute.

    var button = document.getElementById('button');
    
    button.onclick = myfunction;
    
    function myfunction() {
      var name = this.getAttribute('data-name');
      alert(name);
    }
    

    DEMO

    0 讨论(0)
  • 2021-02-04 11:13

    Change your code to

    document.write("<td width='74'><button id='button' type='button' onclick='myfunction(\""+ name + "\")'>click</button></td>")
    
    0 讨论(0)
  • 2021-02-04 11:15

    Rename your variable name to myname, bacause name is a generic property of window and is not writable in the same window.

    And replace

    onclick='myfunction(\''" + name + "'\')'
    

    With

    onclick='myfunction(myname)'
    

    Working example:

    var myname = "Mathew";
    document.write('<button id="button" type="button" onclick="myfunction(myname);">click</button>');
    function myfunction(name) {
        alert(name);
    }

    0 讨论(0)
  • 2021-02-04 11:18

    You can pass string parameters to JavaScript functions like below code:

    I passed three parameters where the third one is a string parameter.

    var btn ="<input type='button' onclick='RoomIsReadyFunc(" + ID + "," + RefId + ",\"" + YourString + "\");'  value='Room is Ready' />";
    
    // Your JavaScript function
    
    function RoomIsReadyFunc(ID, RefId, YourString)
    {
        alert(ID);
        alert(RefId);
        alert(YourString);
    }
    
    0 讨论(0)
提交回复
热议问题