- 我使用一组单选按钮动态生成了问题。然而,我选择和处理静态内容没有问题。我搜索并发现需要委托(delegate)的事件,并且我使用了 on() 方法,但它不起作用。
- 我正在考虑使用 html 中指定的 onclick 方法以及动态生成的内容。好用吗?
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);
});
最佳答案
由于您的表单是动态创建到 DOM 的,因此这些单选按钮的单击事件将不可用。在这种情况下,事件委托(delegate)将帮助您附加该事件。
$(document).on('click', 'input:radio', function (event) {
// ...
});
使用事件委托(delegate)将事件附加到动态元素
关于javascript - JQuery 不处理/从动态内容中选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24202126/