这是我的 HTML:
<div class="tour" data-daily-price="357">
<h2>Paris, France Tour</h2>
<p>$<span id="total">2,499</span> for <span id="nights-count">7</span> Nights</p>
<p>
<label for="nights">Number of Nights</label>
</p>
<p>
<input type="number" id="nights" value="7">
</p>
</div>
这是我的错误代码,用于更改 span 元素的测试以读取我在数字输入中键入的内容。
$(document).ready(function() {
$("#nights").on("keyup", function() {
$("#nights-count").text($("#nights").val());
});
});
这是正确的代码:
$(document).ready(function() {
$("#nights").on("keyup", function() {
$("#nights-count").text($(this).val());
});
});
为什么我需要使用 self 而不是 #nights 才能实现此功能?
最佳答案
If you have multiple id with name
#nights
in your document then default it select first one id with id#nights
. wherethis
will indicating the current selected DOM element instead of#nights
id. If you usethis
it indicate to current selected DOM element, that's why you get correct output in your case there is multiple id with#nights
.
关于javascript - 使用 jquery 和 javascript 遍历 dom 的正确方法以及 "this"的用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28667319/