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

核能气质少年 提交于 2019-12-01 12:10:00

问题


This is my code for html

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

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?


回答1:


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



回答2:


You can try this:

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



回答3:


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

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




回答4:


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



回答5:


The second input should be something like that.

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


来源:https://stackoverflow.com/questions/19549254/how-can-i-concatenate-a-parameter-string-in-javascript-function-on-string-in-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!