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

目前,我是这样做的:

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

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

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

我该如何解决这个问题?


当前回答

对于我来说,在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等)。

其他回答

<button style="background-color: gray;color:white;" onclick="displayAlert('the message')">alert</button>
<script>
    function displayAlert(msg){
        alert(msg);
    }

</script>

在Razor中,你可以动态地传递参数:

<a href='javascript:void(0);' onclick='showtotextbox(@Model.UnitNameVMs[i].UnitNameID, "@Model.UnitNameVMs[i].FarName","@Model.UnitNameVMs[i].EngName","@Model.UnitNameVMs[i].Symbol" );'>@Model.UnitNameVMs[i].UnitNameID</a>

没有转义双引号是OP问题的原因。一种易读的方法是使用反引号(MDN)来转义双引号。下面是一个示例解决方案:

my_btn。setAttribute(’onclick’±my_func ($ $ onclick_var1}”、“onclick_var2} ")”);

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

你可以在你的onclick方法中使用这段代码:

<button class="btn btn-danger" onclick="cancelEmployee(\''+cancelButtonID+'\')" > Cancel </button>