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

目前,我是这样做的:

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

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

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

我该如何解决这个问题?


当前回答

下面是我正在使用的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>

其他回答

试试这个…

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

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

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

let task = {....}

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

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

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