javascript - 使用 jquery 和 javascript 遍历 dom 的正确方法以及 "this"的用法

标签 javascript jquery dom

这是我的 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. 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.

关于javascript - 使用 jquery 和 javascript 遍历 dom 的正确方法以及 "this"的用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28667319/

相关文章:

javascript - 转换 React 项目时出现 Typescript 错误

javascript - 如何使用 jszip 压缩 pdf 或 ppt 文件?

Javascript 不工作我把它放在 jquery 的 dom.ready 中

jQuery -> 选定元素到 HTML

jquery - 两个 Bootstrap 模式并排响应

javascript - 如何在 Laravel 中通过 jQuery AJAX 发布文件和数据

javascript - 如何在节点列表上使用带有 for 循环的 match() 方法

javascript - 将新图像 DOM 对象附加到 <div>

javascript - 我一直试图用 javascript 创建动态排行榜

javascript - 如何选择没有 id 或 class 的嵌套元素?