2014-10-10 61 views
0

我正在使用Handlebars.js輸出一系列問題/答案表單。每個問題只有1個答案,所以我使用<input type="radio">。下面的代碼會產生所需的結果,但是當選中一個單選按鈕時,jQuery change事件不會觸發。jQuery更改事件不適用於輸入:Handlebars.js模板中的單選按鈕

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

回答

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()這個問題給出了附加的事件處理程序的一些很好的啓示,動態生成的元素

+0

完美,謝謝! – atb 2014-10-10 18:15:54

+0

非常歡迎:) – 2014-10-10 18:28:42

相關問題