如何在附加的 html 中的字符串上连接 javascript 函数中的参数字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19549254/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 15:56:30  来源:igfitidea点击:

How Can I concatenate a parameter string in javascript function on string in appended html?

javascriptjqueryhtmlappendconcatenation

提问by Tabares

This is my code for html

这是我的 html 代码

 <div id="content"></div> 

Then I append an inpunt to #content:

然后我将一个输入附加到#content:

 $( document ).ready(function() {
  // Handler for .ready() called.
       var parameter = "<p>Hola</p>";
       $("#content").append('<div><p>click the button</p>'+
                     '<input type="submit" name="submit_answers" value="Submit" onclick="getValue();" >'+  
                     '<input type="submit" name="submit_answers" value="Submit" onclick="'+getValue2(parameter)+'" >'+                        
                     '</div>');
});

function getValue2(parameter){
    alert(parameter);
}

function getValue(){
    alert("Hola");
}

The first input works very well, but the second input dosen′t work after document is ready. What′s the better way to declare a function in this case?

第一个输入效果很好,但是文档准备好后第二个输入不起作用。在这种情况下声明函数的更好方法是什么?

回答by anvoz

You can try this:

你可以试试这个:

'<input type="submit" name="submit_answers" value="Submit" onclick="getValue2(\'' + parameter + '\');" >'

回答by Jason P

You could do this:

你可以这样做:

onclick="getValue2("' + parameter + '")"

But something like this would be better:

但这样的事情会更好:

var $div = $('<div><p>click the botton</p></div>');
var $button = $('<input type="submit" name="submit_answers" value="Submit">')
    .data('parameter', parameter)
    .click(function () {
        getValue2($(this).data('parameter'));
    }).appendTo($div);

$("#content").append($div);

回答by lajili houssem

I think you probably just weren't separating correctly. Try this exemple:

我想你可能只是没有正确分离。试试这个例子:

onclick="mySup(\''+json.id+'\',\''+json.description+'\');"

onclick="mySup(\''+json.id+'\',\''+json.description+'\');"

回答by Aurelin

Try this :

试试这个 :

$( document ).ready(function() {
// Handler for .ready() called.
   var parameter = "<p>Hola new</p>";
   $("#content").append('<div><p>click the botton</p>'+
                 '<input type="submit" name="submit_answers" value="Submit" onclick="getValue();" >'+  
                 '<input type="submit" name="submit_answers" value="Submit" onclick="getValue2(\''+parameter+'\');" >'+                        
                 '</div>');
});

回答by ius

The second input should be something like that.

第二个输入应该是这样的。

'<input type="submit" name="submit_answers" value="Submit" onclick="getValue2('+parameter+')" >'