如何在附加的 html 中的字符串上连接 javascript 函数中的参数字符串? [英] How Can I concatenate a parameter string in javascript function on string in appended html?

查看:25
本文介绍了如何在附加的 html 中的字符串上连接 javascript 函数中的参数字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的 html 代码

This is my code for html

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

然后我在#content 后面附加一个输入:

Then I append an inpunt to #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?

推荐答案

你可以这样做:

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

但这样的事情会更好:

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

这篇关于如何在附加的 html 中的字符串上连接 javascript 函数中的参数字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆