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

时间:2022-09-17 10:54:40

This question already has an answer here:

这个问题在这里已有答案:

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>

4 个解决方案

#1


121  

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

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

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
});

#2


5  

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 $.getJSON function, 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 on on it.

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

jQuery On Method

jQuery On Method

#3


2  

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函数都可以使用这个元素

#4


0  

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创建的语法以某种方式关闭。

#1


121  

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

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

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
});

#2


5  

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 $.getJSON function, 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 on on it.

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

jQuery On Method

jQuery On Method

#3


2  

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函数都可以使用这个元素

#4


0  

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创建的语法以某种方式关闭。