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

目前,我是这样做的:

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

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

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

我该如何解决这个问题?


当前回答

你可以用这个:

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

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

这对我很管用。

其他回答

多个参数:

bounds.extend(marker.position);
bindInfoWindow(marker, map, infowindow,
    '<b>' + response[i].driver_name + '</b><br>' +
    '<b>' + moment(response[i].updated_at).fromNow() + '</b>
     <button onclick="myFunction(\'' + response[i].id + '\',\'' + driversList + '\')">Click me</button>'
);

你也可以在字符串中使用重音符号(')

Try:

`<input type="button" onClick="gotoNode('${result.name}')" />`

欲了解更多信息,请访问MDN和Stack Overflow。

由Chrome, Edge, Firefox (Gecko), Opera, Safari支持,但不支持Internet Explorer。

<!----  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>

这是一种发送值或对象的好方法。

<!DOCTYPE html>
<html>
    <body>
        <h1  onclick="test('wow',this)">Click on this text!</h1>
        <script>
            var test = function(value,object) {
                object.innerHTML= value;
            };
        </script>
    </body>
</html>

对于我来说,在onClick中使用字符串转义有几个问题,随着参数数量的增长,它将变得难以维护。

下面的方法将具有一跳-点击-将控件带到处理程序方法,处理程序方法基于事件对象,可以扣除点击事件和相应的对象。

它还提供了一种更清晰的方式来添加更多参数,并具有更大的灵活性。

<button type="button"
        className="btn btn-default"
        onClick="invoke"
        name='gotoNode'
        data-arg1='1234'>GotoNode</button>

在JavaScript层:

  invoke = (event) => {
    let nameOfFunction = this[event.target.name];
    let arg1 = event.target.getAttribute('data-arg1');
    // We can add more arguments as needed...
    window[nameOfFunction](arg1)
    // Hope the function is in the window.
    // Else the respective object need to be used
    })
  }

这里的优点是我们可以根据需要拥有任意多的参数(在上面的例子中,data-arg1, data-arg2等)。