jquery - 동적으로 만든 단추에 대해 작동하지 않는 이벤트 클릭
저의 요구사항은 json 배열 개수와 동일한 개수의 버튼을 만드는 것입니다.jquery에서 동적으로 버튼을 만드는 데 성공했습니다.그러나 jquery의 .ready 함수의 메서드는 클릭 작업에 대해 호출되지 않습니다.SO에서 검색해 보았습니다.해결책을 거의 찾지 못했지만 아무것도 효과가 없었습니다.저는 잡동사니가 처음입니다.제발 도와주세요...
내 코드: 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>.
<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 -- 샘플 .on 메서드 코드 - 별도 파일: WORKING - THANKS ALLY
<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을 사용하는 경우 방법
그러나 이 메서드는 최신 버전에서는 더 이상 사용되지 않습니다(여기서는 모든 사용되지 않는 메서드의 목록을 볼 수 있습니다).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
});
제 생각에 당신이 만든 버튼은 당신이 단추를 묶을 때까지 아직 페이지에 없는 것 같습니다.의 각 버튼을 바인딩합니다.$.getJSON
함수 또는 다음과 같은 동적 바인딩 메서드를 사용합니다.
$('body').on('click', 'button', function() {
...
});
참고로 '바디' 태그에서 이 작업을 수행하고 싶지 않을 수도 있지만, 대신 버튼을 다른 디브나 무언가에 싸서 호출합니다.on
그 위에
이를 위한 간단하고 쉬운 방법은 이벤트에 사용하는 것입니다.
$('body').on('click','#element',function(){
//somthing
});
우리는 이것이 최선의 방법은 아니라고 말할 수 있습니다.이를 위한 또 다른 방법은 동적 html을 사용하는 대신 clone() method를 사용하는 것을 제안합니다.예를 들어 파일에 html을 작성합니다.
<div id='div1'></div>
이제 스크립트 태그에서 이 div의 클론을 만들면 이 div의 모든 속성이 새 요소와 함께 따라옵니다.예:
var dynamicDiv = jQuery('#div1').clone(true);
이제 dynamicDiv 요소를 원하는 곳에 추가하거나 원하는 대로 속성을 변경할 수 있습니다.이제 모든 jQuery 함수가 이 요소와 함께 작동합니다.
다음과 같은 방법으로 입력 버튼을 만들 수도 있습니다.
var button = '<input type="button" id="questionButton" value='+variable+'> <br />';
버튼 생성의 구문이 어떻게든 해제되어 있을 수 있습니다.
언급URL : https://stackoverflow.com/questions/20819501/jquery-click-event-not-working-for-dynamically-created-button
'itsource' 카테고리의 다른 글
C에서 포인터를 변경하는 것은 원자 작용으로 간주됩니까? (0) | 2023.09.14 |
---|---|
jQuery : blur() 이벤트 전 fire click() 이벤트 (0) | 2023.09.14 |
하나의 스키마를 다른 새 스키마(Oracle)로 가져오기 (0) | 2023.09.14 |
매개 변수에서 사용할 때? (0) | 2023.09.04 |
런타임 오류:이 이벤트 루프가 python에서 이미 실행되고 있습니다. (0) | 2023.09.04 |