简体   繁体   中英

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

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?

你可以试试这个:

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

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

I think you probably just weren't separating correctly.

Try this example :

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM