简体   繁体   中英

Dynamic button click doesn't work in Jquery

I want to develop dynamic presentation content in HTML5 presentation from

http://www.script-tutorials.com/creating-an-attractive-presentation-with-html5/

This tutorial is ok for static content . But I want to write dynamic content with jquery as the following:

$(document).ready(function(){

            $.getJSON(url, function (data) {

                   for(var i in data)
                       {                             
                        output=" <button title='Next' id='nav-next' class='nav-next'>Click</button>";                      
                       }

                    $("#placeholder").append(output);
                });
 });

When click on button , I want to go next slide. But this event does not work. I want to call next function on javascript file. Please help.

You said "When click on button" and that is the answer use jQuery.on() method.

$('#nav-next').on('click',(function () {
     // click code.
});

and then when you created DOM with id defined in .on will have click event dynamically attached.

You're not attaching an event to the new button, this can be done using the jQuery click method.

Also some other problems:

  • the loop seems to be redundant, you're not actually using anything in data .
  • output is being defined as a global variable in your example, use var to keep it in function scope.

Code:

$(document).ready(function() {
    $.getJSON(url, function (data) {

        // use var, your output was a global variable
        var output = " <button title='Next' id='nav-next' class='nav-next'>Click</button>";                      

        $("#placeholder").append(output);

        // attach the click event to the new button
        $('#nav-next').click(function () {
            // TODO: Implement click method
        });
    });
});

Since you're not using data you can remove the call to getJSON safely currently. I assume you put it in for some reason though.

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