【问题标题】:jquery - Click event not working for dynamically created button [duplicate]jquery - 单击事件不适用于动态创建的按钮[重复]
【发布时间】:2014-01-16 03:44:23
【问题描述】:

我的要求是创建等于 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);
}

HTML content
<form method="post" name="formRadio">

<label id="questionNumber"></label>. &nbsp;
<label id="questionDescription"></label>   <br />
<input type="radio" id="optionA"> </input> <label for="optionA"></label> <br />
<input type="radio" id="optionB"> </input> <label for="optionB"></label> <br />
<input type="radio" id="optionC"> </input> <label for="optionC"></label> <br />

<button id="previousQuestion">Previous Question</button>
<button id="nextQuestion">Next Question</button>

<br />
<br />

<input type="submit" id="submitButton" name="submitTest" value="Submit"></input>
</form>

编辑 - 示例 .on 方法代码 - 单独的文件:工作 - 非常感谢

<script>
$(document).ready(function()
{
    $("button").click(function()
    {
        var button = '<input type="button" id="button2" value="dynamic button">';
        $('body').append(button);
    });
});

$(document).on('click','#button2', function()
{
    alert("Dynamic button action");
});

</script>
</head>

<body>

<button id="button">Static Button</button>

</body>

【问题讨论】:

  • @Barmer 谁能告诉我为什么下面的代码不起作用? $(document).on('click', 'button', function(e) { alert("asd"); });

标签: jquery html


【解决方案1】:

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

但此方法在较新版本中已弃用(您可以查看所有弃用方法 here 的列表)。如果您想使用 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
});

【讨论】:

  • 这个方法太棒了。它使用文档对象并找到那里的任何按钮,无论是旧的还是新的(动态创建的)。
  • @majid, 甚至 $(document).on('click', 'button', function(){ alert("asd"); });不工作....点击动态创建的按钮,警报没有弹出...任何帮助将不胜感激...
  • @vivin,我在我的答案中添加了一个示例
  • @majid... 完成,先生。再澄清一件事。在我的 getjson 函数中,我有 questionsArray。当我尝试访问 question.questionNumber 时,我收到一条“未定义”消息。我的 json 看起来像 [{"questionNumber":"1","quesDesc":"The price...?","optionA":"25%",...,"selectedAnswer":null},{"questionNumber ":"2","que‌​sDesc":"价格 ...?","optionA":"9.09%",...,"selectedAnswer":null},...]。格式没有问题。请让我知道如何使用相同的 for 循环访问 json 数据中的值...
  • 我无法在评论中清楚地回答您的问题,但此链接回答您的问题stackoverflow.com/questions/2342371/…
【解决方案2】:

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

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

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

jQuery On Method

【讨论】:

    【解决方案3】:

    简单易行的方法是在事件中使用:

    $('body').on('click','#element',function(){
        //somthing
    });
    

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

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

    现在在脚本标签中克隆这个 div,然后这个 div 的所有属性也将跟随新元素。例如:

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

    现在,无论您想在何处添加元素或更改其属性,都可以使用元素 dynamicDiv。现在所有的 jQuery 函数都可以使用这个元素了

    【讨论】:

      【解决方案4】:

      你也可以这样创建输入按钮:

      var button = '<input type="button" id="questionButton" value='+variable+'> <br />';
      


      可能是按钮创建的语法以某种方式关闭。

      【讨论】:

      • 两者的动作一样吧?还是我们有一些建议的细节?
      猜你喜欢
      • 2019-08-04
      • 1970-01-01
      • 1970-01-01
      • 2012-03-18
      • 1970-01-01
      • 2013-12-13
      • 2020-03-30
      • 2012-12-30
      • 2016-06-30
      相关资源
      最近更新 更多