programing

jquery-동적으로 생성 된 버튼에 대해 클릭 이벤트가 작동하지 않음

nasanasas 2020. 11. 7. 10:10
반응형

jquery-동적으로 생성 된 버튼에 대해 클릭 이벤트가 작동하지 않음


이 질문에 이미 답변이 있습니다.

내 요구 사항은 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>

.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:

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

For Example

If your html is something like this

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

You can write your jquery like this

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

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:

$('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.

jQuery On Method


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:

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

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


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.

참고URL : https://stackoverflow.com/questions/20819501/jquery-click-event-not-working-for-dynamically-created-button

반응형