我使用Handlebars.js输出一系列问题/答案表格。每个问题只有1个答案,所以我使用<input type="radio">
。下面的代码产生了所需的结果,但是当选中单选按钮时,jQuery change
事件没有触发。
<script id="questions-template" type="text/x-handlebars-template">
{{#questions}}
{{questionIndex @index}}
<article class="question question-{{@index}} clearfix">
<h2>{{question}}</h2>
<form>
{{#each answers}}
<div class="answer">
<input type="radio" name="radios[{{../questionIndex}}]" id="radios-{{../questionIndex}}{{@index}}" value="{{value}}">
<label for="radios-{{../questionIndex}}{{@index}}"><span>{{answer}}</span></label>
</div>
{{/each}}
</form>
</article>
{{/questions}}
</script>
<div id="questions"></div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0/handlebars.min.js"></script>
<script>
$(function(){
var questions = {
"questions": [
{
"question": "Lorem ipsum dolor sit amet, consectetur adipiscing elit?",
"answers": [
{
"answer": "Answer 1",
"value": 1
},
{
"answer": "Answer 2",
"value": 2
}
]
}
]
};
$(document).ready(function(event) {
var
source = $("#questions-template").html(),
template = Handlebars.compile(source);
Handlebars.registerHelper('questionIndex', function(value) {
this.questionIndex = Number(value);
});
$('#questions').append(template(questions));
});
$('input:radio').change(function(event) {
alert('change');
});
});
</script>
答案 0 :(得分:1)
您应该使用.on来分配您的事件处理程序 - 因为您的单选按钮是动态生成的。试试这个:
$("#questions").on("change", "input:radio", function(event) {//assuming questions is already part of the DOM
alert('change');
});
这个问题Why use jQuery on() instead of click()提供了一些关于将事件处理程序附加到动态生成元素的一些好的见解