HTML代码:动态生成的内容会附加到'问题表单中。
<section id="questions-form"></section>
<!-- dynamically generated questions with radio options
<form id="question_0" role="form" class="card">
<div class="form-group">
<section>1. Newtons first law of motion gives the concept of</section>
<div class="btn-group">
<label class="checkbox" for="option_0_1">
<input type="radio" name="q_0" value="a" id="option_0_1">force</label>
<label class="checkbox" for="option_0_2">
<input type="radio" name="q_0" value="b" id="option_0_2">momentum</label>
<label class="checkbox" for="option_0_3">
<input type="radio" name="q_0" value="c" id="option_0_3">work</label>
<label class="checkbox" for="option_0_4">
<input type="radio" name="q_0" value="d" id="option_0_4">inertia</label>
</div>
<br>
<div class="btn-group">
<button class="mark btn btn-danger">MARK</button>
<button class="mark btn btn-warning">SKIP</button>
</div>
</div>
</form>
<form id="question_1" role="form" class="card">
<div class="form-group">
<section>2. Inertia of body depends on</section>
<div class="btn-group">
<label class="checkbox" for="option_1_1">
<input type="radio" name="q_1" value="a" id="option_1_1">velocity</label>
<label class="checkbox" for="option_1_2">
<input type="radio" name="q_1" value="b" id="option_1_2">mass</label>
<label class="checkbox" for="option_1_3">
<input type="radio" name="q_1" value="c" id="option_1_3">area</label>
<label class="checkbox" for="option_1_4">
<input type="radio" name="q_1" value="d" id="option_1_4">none of these</label>
</div>
<br>
<div class="btn-group">
<button class="mark btn btn-danger">MARK</button>
<button class="mark btn btn-warning">SKIP</button>
</div>
</div>
-->
JQuery的:
$('input:radio').on('click', this, function (event) {
event.preventDefault();
console.log("from input radio");
var question = $(this).closest("form").attr("id");
var selected = $(this).val();
var msg = question + " " + selected;
alert(msg);
});
答案 0 :(得分:1)
由于您的表单动态创建到DOM,因此单击事件将不适用于这些单选按钮。在这种情况下,事件委派将帮助您附加该事件。
$(document).on('click', 'input:radio', function (event) {
// ...
});
使用事件委派将事件附加到动态元素
答案 1 :(得分:0)
这是正确的方法。
参考jQuery .on()
$(document).on('click', 'input:radio', function (event) {
event.preventDefault();
console.log("from input radio");
var question = $(this).closest("form").attr("id");
var selected = $(this).val();
var msg = question + " " + selected;
alert(msg);
});
答案 2 :(得分:0)
尝试使用jquery live() API,如下所示:
$('input:radio').live('click', this, function (event) {
event.preventDefault();
console.log("from input radio");
var question = $(this).closest("form").attr("id");
var selected = $(this).val();
var msg = question + " " + selected;
alert(msg);
});
答案 3 :(得分:0)
使用活动授权:http://www.sitepoint.com/event-delegation-with-jquery/
因为事件委托允许我们将单个事件侦听器附加到父元素,该元素将为匹配选择器的所有后代触发,无论这些后代现在是存在还是将来添加。
$(document).on('click', 'input:radio', function (event) { //.... });