我有以下 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 中检查控制台时,看起来我点击哪个标签并不重要;控制台只打印第一个 li
的 id“first”。我怎样才能让它检索相应的 li
单击?
最佳答案
修改answerSelect()
方法:
function answerSelect() {
$("body").on("click", "li input", function(e) {
let selectedAnswer = e.target.id;
console.log(selectedAnswer);
});
}
关于javascript - jQuery:在点击时检索 DOM 的 ID 仅返回第一次点击的 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53532729/