在onclick函数中传递字符串参数

时间:2012-03-10 02:05:49

标签: javascript html

我想将参数(即字符串)传递给Onclick函数。目前,我这样做:

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

,例如result.name等于字符串“Add”。 当我单击此按钮时,出现错误,指出未定义添加。由于这个函数调用与数字参数完美配合,我认为它与字符串中的符号“”有关。 以前有没有人遇到这个问题?

25 个答案:

答案 0 :(得分:297)

看起来你正在从字符串构建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);​

请注意,如果这是一个循环或某事,result将在事件触发之前发生变化,您需要创建一个额外的范围气泡来遮蔽变化的变量。

答案 1 :(得分:23)

我建议您不要使用HTML onclick处理程序,并使用更常见的内容,例如document.getElementById

HTML:

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

JavaScript的:

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

答案 2 :(得分:22)

关于在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 args as needed...
    window[nameOfFunction](arg1) 
    //hope function is in window. 
    //Else the respective object need to be used 
    })
  }

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

答案 3 :(得分:19)

我猜,你正在使用JavaScript本身创建一个按钮。因此,代码中的错误是,它将以此形式呈现

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

在当前状态下,add将被视为变量或函数调用之类的标识符。你应该像这样逃避价值

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

答案 4 :(得分:13)

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

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

答案 5 :(得分:6)

试试这个..

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>

注意:确保在&#39;之间发送参数&#39; html代码中的符号(&#39; a1&#39;)

答案 6 :(得分:5)

多个参数:

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

答案 7 :(得分:4)

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

您可以将字符串参数传递给javascript函数,例如以下代码:

我传递了3个参数,其中第三个是字符串参数,希望对您有所帮助。

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

答案 8 :(得分:4)


编辑: 如果要求是在HTML代码中引用全局对象(js),则可以尝试这样做。 [不要在变量周围使用任何引号('或“)

Fiddle 参考。

使用Javascript:

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

HTML:

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

答案 9 :(得分:2)

你也在字符串

中使用重音符号(`)

尝试:

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

有关详细信息,请访问MDNStackoverflow

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

答案 10 :(得分:1)

对于传递多个参数,您可以通过将其与ASCII值连接来强制转换字符串,对于单引号我们可以使用'

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

答案 11 :(得分:1)

你可以传递引用或字符串值,只需将函数放在双逗号“”asp下面的快照

enter image description here

答案 12 :(得分:0)

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

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

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

答案 13 :(得分:0)

if用于生成具有不同处理程序参数的一组按钮。 https://www.w3schools.com/js/js_function_closures.asp

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”的最后一个值

答案 14 :(得分:0)

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

答案 15 :(得分:0)

如果您使用的是ASP,则可以使用javascript:

HTML:

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

Javascript:

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

答案 16 :(得分:0)

如果您正在动态添加按钮或链接并面临问题,那么这可能会有所帮助。我通过这种方式解决了。

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

我是HTML,JQuery和JS的新手。所以可能我的代码不会得到优化或语法,但是对我有用。

答案 17 :(得分:0)

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>

答案 18 :(得分:0)

您可以使用此:

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

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

对我有用。

答案 19 :(得分:0)

如果您需要将变量与'this'关键字一起传递,则以下代码有效:

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

答案 20 :(得分:0)

let task = {....}

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

答案 21 :(得分:0)

不转义双引号是 OP 问题的原因。转义双引号的一种可读方法是使用反引号 (MDN)。这是一个示例解决方案:

my_btn.setAttribute('onclick', `my_func("${onclick_var1}", "${onclick_var2}")`);

答案 22 :(得分:-1)

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

答案 23 :(得分:-1)

您可以在JavaScript文件中使用此代码添加按钮:

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

答案 24 :(得分:-1)

<!----  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>
相关问题