Мое требование - создать количество кнопок, равное счету json array. Мне удалось создать динамические кнопки в jQuery. Но метод в .ready функции jquery не вызван для действия click. Я пробовал искать в 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>.
<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 - СПАСИБО LOT
<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>