Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

My task is to add button dynamically to the div.. here is the code that i follow to add button dynamically but its not working please give me a solution for this

<!DOCTYPE html>
    <html>
    <head>
         <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
         <script type="text/javascript">
             function test() {
                var r = "$('<input/>').attr({
                             type: "button",
                             id: "field"
                        })";
             }
             $("body").append(r);
         </script>
    </head>
    <body>
         <button onclick="test()">Insert after</button> 
    </body>
    </html>

code to append button on div when page loads but its not working

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
function test() {
    var r=$('<input/>').attr({
        type: "button",
        id: "field"

    });
    test().append("#test");    
}
</script>
</head>
<body>
<div id="test"></div>
 <button id="insertAfterBtn" onclick="test()">Insert after</button>
</body>
</html>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
95 views
Welcome To Ask or Share your Answers For Others

1 Answer

Your append line must be in your test() function

EDIT:

Here are two versions:

Version 1: jQuery listener

$(function(){
    $('button').on('click',function(){
        var r= $('<input type="button" value="new button"/>');
        $("body").append(r);
    });
});

DEMO HERE

Version 2: With a function (like your example)

function createInput(){
    var $input = $('<input type="button" value="new button" />');
    $input.appendTo($("body"));
}

DEMO HERE

Note: This one can be done with either .appendTo or with .append.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...