我有以下HTML,这些HTML是在页面加载后的某个时间附加的。
我有以下JS,我正在尝试检索单击的标签的ID或与之关联的输入ID。
function answerSelect(){
$("body").on("click", "li label", function(){
let selectedAnswer = $("input").attr("id");
console.log(selectedAnswer);
})
}
answerSelect();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<div class="questions-container">
<form>
<ul>
<h2 class="question">This is a question?</h2>
<li>
<input id="first" type="radio" name="answer-choice" required>
<label for="first">1</label>
</li>
<li>
<input id="second" type="radio" name="answer-choice">
<label for="second">2</label>
</li>
<li>
<input id="third" type="radio" name="answer-choice">
<label for="third">3</label>
</li>
<li>
<input id="fourth" type="radio" name="answer-choice">
<label for="fourth">4</label>
</li>
</ul>
<button class ="start submit btn"><h2>Submit</h2></button>
</form>
</div>
</body>
当前,在Chrome中检查控制台时,我单击哪个标签似乎无关紧要;控制台仅显示id“ first”,即第一个li
。我如何才能使它检索到相应的点击的li
?
答案 0 :(得分:1)
请改用change
侦听器(这样,单击input
和的同时单击label
都会触发侦听器),然后使用:checked
伪选择器进入已检查的input
:
$("body").on("change", "li > input", function(e) {
let selectedAnswer = $("input:checked").attr("id");
console.log(selectedAnswer);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="questions-container">
<form>
<ul>
<h2 class="question">This is a question?</h2>
<li>
<input id="first" type="radio" name="answer-choice" required>
<label for="first">1</label>
</li>
<li>
<input id="second" type="radio" name="answer-choice">
<label for="second">2</label>
</li>
<li>
<input id="third" type="radio" name="answer-choice">
<label for="third">3</label>
</li>
<li>
<input id="fourth" type="radio" name="answer-choice">
<label for="fourth">4</label>
</li>
</ul>
<button class="start submit btn"><h2>Submit</h2></button>
</form>
</div>
答案 1 :(得分:1)
修改answerSelect()
方法:
function answerSelect() {
$("body").on("click", "li input", function(e) {
let selectedAnswer = e.target.id;
console.log(selectedAnswer);
});
}
答案 2 :(得分:0)
答案 3 :(得分:0)
替换下面的代码:
function answerSelect(){
$("body").on("click", "li label", function(){
let selectedAnswer = $("input").attr("id");
console.log(selectedAnswer);
})
}
使用
$(document).on("click", "input[type='radio']", function(){
let selectedAnswer = $("input").attr("id");
console.log(selectedAnswer);
})