我正在使用Handlebars.js输出一系列问题/答案表格。每个问题只有1个答案,所以我正在使用<input type="radio">
。下面的代码产生所期望的结果然而当无线电按钮被选中了jQuerychange
事件不点火。
<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>
您应该使用.on来分配事件处理程序-因为您的单选按钮是动态生成的。试试这个:
$("#questions").on("change", "input:radio", function(event) {//assuming questions is already part of the DOM
alert('change');
});
为什么在这里使用jQuery on()而不是click()可以很好地理解将事件处理程序附加到动态生成的元素上的方法
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句