jQuery-Click事件不适用于动态创建的按钮

我的要求是创建等于json数组计数的按钮数。我成功地在jquery中动态创建了按钮。但是单击动作不会调用jquery的.ready函数中的方法。我曾尝试在SO中搜索。找不到解决方案,但对我没有任何帮助。我对jquery非常陌生。请帮忙...


我的代码:jQuery:


$(document).ready(function()

{

    currentQuestionNo = 0;

    var questionsArray;

    $.getJSON('http://localhost/Sample/JsonCreation.php', function(data)

    {   

        questionsArray = data;

        variable = 1;

            //CREATE QUESTION BUTTONS DYNAMICALLY ** NOT WORKING

        for (var question in questionsArray)

        {

            var button = $("<input>").attr("type", "button").attr("id", "questionButton").val(variable);


            $('body').append(button);


                        //Tried using .next here - but it dint work...

            //$('body').append('<button id="questionButton">' + variable + '</button>');

            variable++;

        }

        displayQuestionJS(questionsArray[currentQuestionNo], document);

    });





    $("button").click(function()

    {


        if ($(this).attr('id') == "nextQuestion")

        {

            currentQuestionNo = ++currentQuestionNo;

        }

        else if ($(this).attr('id') == "previousQuestion")

        {

            currentQuestionNo = --currentQuestionNo;

        }


        displayQuestionJS(questionsArray[currentQuestionNo], document);


    });




function displayQuestionJS(currentQuestion, document) 

{

    document.getElementById('questionNumber').innerText  = currentQuestion.questionNumber;

    document.getElementById('questionDescription').innerText  = currentQuestion.quesDesc;

    $('label[for=optionA]').html(currentQuestion.optionA);

    $('label[for=optionB]').html(currentQuestion.optionB);

    $('label[for=optionC]').html(currentQuestion.optionC);

}

慕慕森
浏览 592回答 3
3回答

三国纷争

动态创建按钮是因为,.live()如果使用jquery 1.7,则需要使用方法调用它们但此方法已在新版本中弃用(您可以在此处查看所有弃用方法的列表)。如果要使用jquery 1.10或更高版本,则需要以这种方式调用按钮:$(document).on('click', 'selector', function(){&nbsp;&nbsp; &nbsp; &nbsp;// Your Code});例如如果您的html是这样的<div id="btn-list">&nbsp; &nbsp; <div class="btn12">MyButton</div></div>你可以这样写你的jQuery$(document).on('click', '#btn-list .btn12', function(){&nbsp;&nbsp; &nbsp; &nbsp;// Your Code});

慕后森

我的猜测是,当您绑定按钮时,您创建的按钮尚未出现在页面上。绑定$.getJSON函数中的每个按钮,或使用动态绑定方法,例如:$('body').on('click', 'button', function() {&nbsp; &nbsp; ...});注意,您可能不想在'body'标签上执行此操作,而是将按钮包装在另一个div或其他内容中并对其进行调用on。

红糖糍粑

做到这一点的简单方法是在事件上使用:$('body').on('click','#element',function(){&nbsp; &nbsp; //somthing});但是我们可以说这不是最好的方法。我建议另一种方法是使用clone()方法,而不是使用动态html。例如,在您的文件中写一些html:<div id='div1'></div>现在,在脚本标签中对此div进行克隆,然后该div的所有属性也将带有新元素。例如:var dynamicDiv = jQuery('#div1').clone(true);现在,您可以在想要添加元素或更改其属性的任何位置使用它。现在,所有jQuery函数都可以与此元素一起使用
打开App,查看更多内容
随时随地看视频慕课网APP