使用 jquery 和 javascript 遍历 dom 的正确方法以及 "this" 的用法
Proper way to traverse the dom with jquery and javascript and usage of "this"
这是我的 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 才能工作?
它应该可以正常工作,除非 #nights
不是唯一 ID。例如,如果有多个 "tour"
div,每个 div 都有一个 #nights
元素。也就是说,$(this)
更好,因为它不需要 jQuery 去再次解析 DOM...
If you have multiple id with name #nights
in your document then default it select first one id with id #nights
. where this
will indicating the current selected DOM element instead of #nights
id. If you use this
it indicate to current selected DOM element, that's why you get correct output in your case there is multiple id with #nights
.
问题是您有超过 1 个 ID 为 nights
的元素。您的第一段代码有效:http://jsfiddle.net/fomd990c/
如果您有另一个 ID 为 nights
的元素,则不会:http://jsfiddle.net/fomd990c/1/
将特定 id 限制为仅一个元素通常是个好主意。
这是我的 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 才能工作?
它应该可以正常工作,除非 #nights
不是唯一 ID。例如,如果有多个 "tour"
div,每个 div 都有一个 #nights
元素。也就是说,$(this)
更好,因为它不需要 jQuery 去再次解析 DOM...
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
.
问题是您有超过 1 个 ID 为 nights
的元素。您的第一段代码有效:http://jsfiddle.net/fomd990c/
如果您有另一个 ID 为 nights
的元素,则不会:http://jsfiddle.net/fomd990c/1/
将特定 id 限制为仅一个元素通常是个好主意。