我想传递一个参数(即字符串)到Onclick函数。

目前,我是这样做的:

'<input type="button" onClick="gotoNode(' + result.name + ')" />'

例如,result.name = string "Add"。

当我点击这个按钮时,我有一个错误,说“Add is not defined”。由于这个函数调用可以很好地处理数值形参,所以我假设它与字符串中的符号“”有关。

我该如何解决这个问题?


当前回答

试试这个…

HTML:

<button id="a1" type="button" onclick="return a1_onclick('a1')">a1</button>

JavaScript:

<script language="javascript" type="text/javascript">
    function a1_onclick(id) {
        document.getElementById(id).style.backgroundColor = "#F00";
    }
</script>

注意:在HTML代码中,请确保在('a1')等符号之间发送参数

其他回答

<!----  script ---->
<script>
function myFunction(x) {
  document.getElementById("demo").style.backgroundColor = x; 
}
</script>

<!---- source ---->
<p id="demo" style="width:20px;height:20px;border:1px solid #ccc"></p>

<!----  buttons & function call ----> 
<a  onClick="myFunction('red')" />RED</a> 
<a  onClick="myFunction('blue')" />BLUE</a> 
<a  onClick="myFunction('black')" />BLACK</a>
<button style="background-color: gray;color:white;" onclick="displayAlert('the message')">alert</button>
<script>
    function displayAlert(msg){
        alert(msg);
    }

</script>

试试这个…

HTML:

<button id="a1" type="button" onclick="return a1_onclick('a1')">a1</button>

JavaScript:

<script language="javascript" type="text/javascript">
    function a1_onclick(id) {
        document.getElementById(id).style.backgroundColor = "#F00";
    }
</script>

注意:在HTML代码中,请确保在('a1')等符号之间发送参数

你可以用这个:

'<input id="test" type="button" value="' + result.name + '" />'

$(document).on('click', "#test", function () {
    alert($(this).val());
});

这对我很管用。

下面的方法对我很有用,

<html>
<head>
    <title>HTML Form</title>
</head>
<body>
    <form>
        <input type="button" value="ON" onclick="msg('ON')">
        <input type="button" value="OFF" onclick="msg('OFF')">
    </form>
    <script>
        function msg(x){
            alert(x);
        }
    </script>
</body>
</html>