为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕慕森 2019-11-29 10:10:18
我的要求是创建等于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);}
查看完整描述

3 回答

?
三国纷争

TA贡献1804条经验 获得超7个赞

动态创建按钮是因为,.live()如果使用jquery 1.7,则需要使用方法调用它们


但此方法已在新版本中弃用(您可以在此处查看所有弃用方法的列表)。如果要使用jquery 1.10或更高版本,则需要以这种方式调用按钮:


$(document).on('click', 'selector', function(){ 

     // Your Code

});

例如


如果您的html是这样的


<div id="btn-list">

    <div class="btn12">MyButton</div>

</div>

你可以这样写你的jQuery


$(document).on('click', '#btn-list .btn12', function(){ 

     // Your Code

});


查看完整回答
反对 回复 2019-11-29
?
慕后森

TA贡献1802条经验 获得超5个赞

我的猜测是,当您绑定按钮时,您创建的按钮尚未出现在页面上。绑定$.getJSON函数中的每个按钮,或使用动态绑定方法,例如:


$('body').on('click', 'button', function() {

    ...

});

注意,您可能不想在'body'标签上执行此操作,而是将按钮包装在另一个div或其他内容中并对其进行调用on。


查看完整回答
反对 回复 2019-11-29
?
红糖糍粑

TA贡献1815条经验 获得超6个赞

做到这一点的简单方法是在事件上使用:


$('body').on('click','#element',function(){

    //somthing

});

但是我们可以说这不是最好的方法。我建议另一种方法是使用clone()方法,而不是使用动态html。例如,在您的文件中写一些html:


<div id='div1'></div>

现在,在脚本标签中对此div进行克隆,然后该div的所有属性也将带有新元素。例如:


var dynamicDiv = jQuery('#div1').clone(true);

现在,您可以在想要添加元素或更改其属性的任何位置使用它。现在,所有jQuery函数都可以与此元素一起使用


查看完整回答
反对 回复 2019-11-29
  • 3 回答
  • 0 关注
  • 579 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信