jquery - 单击事件不适用于动态创建的按钮

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20819501/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 01:19:43  来源:igfitidea点击:

jquery - Click event not working for dynamically created button

jqueryhtml

提问by vivin

My requirement is to create number of buttons equal to the json array count. I was successful in creating buttons dynamically in jquery. But the method in .ready function of jquery is not called for the click action. I have tried searching in SO. Found few solutions but nothing worked for me. I am very new to jquery. Please help...

我的要求是创建等于 json 数组计数的按钮数。我成功地在 jquery 中动态创建按钮。但是jquery的.ready函数中的方法并没有为点击动作调用。我试过在 SO 中搜索。找到了几个解决方案,但对我来说没有任何效果。我对 jquery 很陌生。请帮忙...

my code: 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>

EDIT -- Sample .on Method code - Separate file: WORKING - THANKS A LOT

编辑 - 示例 .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>

回答by Majid Golshadi

You create buttons dynamically because of that you need to call them with .live()method if you use jquery 1.7

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

but this method is deprecated (you can see the list of all deprecated method here) in newer version. if you want to use jquery 1.10 or above you need to call your buttons in this way:

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

$(document).on('click', 'selector', function(){ 
     // Your Code
});

For Example

例如

If your html is something like this

如果你的 html 是这样的

<div id="btn-list">
    <div class="btn12">MyButton</div>
</div>

You can write your jquery like this

你可以这样写你的jquery

$(document).on('click', '#btn-list .btn12', function(){ 
     // Your Code
});

回答by jrpotter

My guess is that the buttons you created are not yet on the page by the time you bind the button. Either bind each button in the $.getJSONfunction, or use a dynamic binding method like:

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

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

Note you probably don't want to do this on the 'body' tag, but instead wrap the buttons in another div or something and call onon it.

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

jQuery On Method

jQuery On 方法

回答by Aashish

the simple and easy way to do that is use on event:

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

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

but we can say this is not the best way to do this. I suggest a another way to do this is use clone() method instead of using dynamic html. Write some html in you file for example:

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

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

Now in the script tag make a clone of this div then all the properties of this div would follow with new element too. For Example:

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

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

Now use the element dynamicDiv wherever you want to add it or change its properties as you like. Now all jQuery functions will work with this element

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

回答by Bam

You could also create the input button in this way:

您还可以通过这种方式创建输入按钮:

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


It might be the syntax of the Button creation that is off somehow.


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