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

目前,我是这样做的:

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

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

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

我该如何解决这个问题?


如果要求在HTML代码中引用全局对象(JavaScript),您可以尝试这样做。[不要在变量周围使用任何引号('或")]

小提琴参考。

JavaScript:

var result = {name: 'hello'};
function gotoNode(name) {
    alert(name);
}

HTML:

<input value="Hello" type="button" onClick="gotoNode(result.name)" />​

我建议甚至不要使用HTML的onclick处理程序,而使用一些更常见的东西,如document.getElementById。

HTML:

<input type="button" id="nodeGoto" />

JavaScript:

document.getElementById("nodeGoto").addEventListener("click", function() {
    gotoNode(result.name);
}, false);

看起来像是从字符串构建DOM元素。你只需要在result.name周围添加一些引号:

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

不过,您确实应该使用适当的DOM方法来实现这一点。

var inputElement = document.createElement('input');
inputElement.type = "button"
inputElement.addEventListener('click', function(){
    gotoNode(result.name);
});

​document.body.appendChild(inputElement);​

请注意,如果这是一个循环或其他东西,结果将在事件触发之前发生变化,您需要创建一个额外的作用域气泡来掩盖变化的变量。


我猜,您正在使用JavaScript本身创建一个按钮。代码中的错误在于,它会以这种形式呈现

<input type="button" onClick="gotoNode(add)" />'

在当前状态下,add将被视为与变量或函数调用类似的标识符。你应该这样转义这个值

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

试试这个…

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')等符号之间发送参数


您可以传递一个引用或字符串值。只需将函数放在双逗号“”中,如下所示:


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

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

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

Try:

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

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

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


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


多个参数:

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>'
);

要传递多个参数,可以通过将字符串与ASCII值连接来强制转换。比如,对于单引号,我们可以使用&#39;

var str = "&#39;" + str + "&#39;";

可以传递给onclick()事件的相同参数。在大多数情况下,它适用于所有浏览器。


<style type="text/css">
    #userprofile{
        display: inline-block;
        padding: 15px 25px;
        font-size: 24px;
        cursor: pointer;
        text-align: center;
        text-decoration: none;
        outline: none;
        color: #FFF;
        background-color: #4CAF50; // #C32836
        border: none;
        border-radius: 15px;
        box-shadow: 0 9px #999;
        width: 200px;
        margin-bottom: 15px;
    }
    #userprofile:hover {
        background-color: #3E8E41
    }

    #userprofile:active {
        background-color: #3E8E41;
        box-shadow: 0 5px #666;
        transform: translateY(4px);
    }

    #array {
        border-radius: 15px 50px;
        background: #4A21AD;
        padding: 20px;
        width: 200px;
        height: 900px;
        overflow-y: auto;
    }
</style>
if (data[i].socketid != "") {
    $("#array").append("<button type='button' id='userprofile' class='green_button' name=" + data[i]._id + " onClick='chatopen(name)'>" + data[i].username + "</button></br>");
}
else {
    console.log('null socketid  >>', $("#userprofile").css('background-color'));
    //$("#userprofile").css('background-color', '#C32836 ! important');

    $("#array").append("<button type='button' id='userprofile' class='red_button' name=" + data[i]._id + " onClick='chatopen(name)'>" + data[i].username+"</button></br>");
    $(".red_button").css('background-color','#C32836');
}

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

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

下面的方法对我很有用,

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

如果你的按钮是动态生成的:

你可以将字符串参数传递给JavaScript函数,如下所示:

我传递了三个参数,第三个是字符串参数。

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);
}

如果用于生成一组具有不同处理程序参数的按钮。

JavaScript闭包

let some_button = document.createElement( "button" );
some_button.type = "button";

some_button.onclick = doWithParam( some_param );

function doWithParam( param ){
    return function(){
        alert( param ); // <-- Your code here
    }
}

如果我们这样做:

some_button.onclick = foo( some_param );
function foo( param ){
    alert( param );
}

然后函数foo在每个更新页面之后启动。

如果我们这样做:

for( let i = 0; i < 10; ++i ){
    var inputElement = document.createElement('input');
    inputElement.type = "button"
    inputElement.addEventListener('click', function(){
        gotoNode(result.name);
    });

 ​   document.body.appendChild(inputElement);​
}

然后,对于循环中创建的所有按钮,参数的最后一个值是“result.name”。


下面是我正在使用的jQuery解决方案。

jQuery

$("#slideshow button").click(function(){
    var val = $(this).val();
    console.log(val);
});

HTML

<div id="slideshow">
    <img src="image1.jpg">
    <button class="left" value="back">&#10094;</button>
    <button class="right" value="next">&#10095;</button>
</div>

如果您正在使用ASP。NET你可以使用JavaScript:

HTML

<input type='button' value='test' onclick='javascript: EditSelectedOptionName(x,y)' />"

JavaScript

function EditSelectedOptionName(id, name) {
    console.log(id);
    console.log(name);
}

如果您正在动态添加按钮或链接,并面临这个问题,那么这可能会有所帮助。我是这样解决的:

var link= $(contentData1[i]).find("td:first font b a").attr("href",'javascript:onClick=openWin(\'' + tdText + '\')');

我是新的HTML, jQuery和JavaScript。也许我的代码没有优化,语法也没有优化,但它对我有用。


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

你可以用这个:

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

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

这对我很管用。


如果你需要传递一个带有'this'关键字的变量,下面的代码可以工作:

var status = 'Active';
var anchorHTML = '<a href ="#" onClick = "DisplayActiveStatus(this,\'' + status + '\')">' + data+ '</a>';

let task = {....}

<button onclick="myFunction('${task}')">Continue task</button></li>

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

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

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


这是我的工作:

$(element).attr("onClick", 'functionName(' + "\"" + Object.attribute + "\"" + ')');

只需在()中添加\斜杠

※多参数示例

"functionName(" + "'" + parameter1 + "','" + parameter2 + "','" + parameter3 + "','" + parameter4 + "','" + parameter5 + "','" + parameter6 + "')"

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

</script>