【问题标题】:Using find with this returns undefined in Jquery [duplicate]在 Jquery 中使用 find 和 this 返回 undefined [重复]
【发布时间】:2019-12-11 14:21:51
【问题描述】:

我正在尝试遍历具有类名的元素并在其中找到输入值:

 document.querySelectorAll('.qty').forEach(element=>{
        console.log($(this).find('input').val())
    })

这将返回undefined

但是,如果我将上面的代码更改为:

 document.querySelectorAll('.qty').forEach(element=>{
        console.log($('.qty').find('input').val())
    })

this 不应该用数量来引用类名。为什么this 不起作用?

【问题讨论】:

    标签: javascript jquery ecmascript-6


    【解决方案1】:

    因为您使用的箭头函数不包含其自己的this 绑定。使用一个普通的 ES5 函数:

    document.querySelectorAll(".qty").forEach(function(element) {
      console.log($(this).find("input").val());
    });
    

    为了让您的代码更简洁,您可以使用 jQuery 的内置函数,并丢弃未使用的 element 参数。

    $(".qty").each(function() {
      console.log($(this).find("input").val());
    });
    

    或者忘记this并使用参数,这将允许您使用箭头函数:

    $(".qty").each((_, e) => console.log(e.find("input").val()));
    

    【讨论】:

    • 请关闭重复项
    • 我的坏@adiga,我不知道这个问题的重复存在,而且我没有重复问题的列表,因为我对 a 提供的 dupehammer 不太感兴趣金标签徽章需要一个。
    【解决方案2】:
    forEach 中的

    $(this) 表示全局窗口对象。如果您更喜欢使用 jquery,请将其更改为 $('.qty').each 而不是使用 querySelectorAll

    $('.qty').each((i, v) => {
      console.log($(v).find('input').val())
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class='qty'>
      <input type="text" value="1"></div>
    
    <div class='qty'>
      <input type="text" value="1"></div>
    
    <div class='qty'>
      <input type="text" value="1"></div>
    
    <div class='qty'>
      <input type="text" value="1"></div>

    【讨论】:

    • 请关闭重复项
    【解决方案3】:

    这在 javascript 中的行为有点不同。 this 的值取决于函数的调用方式(运行时绑定)。

    更多解释请参考本文档:

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

    【讨论】:

      猜你喜欢
      • 2017-02-18
      • 2017-06-23
      • 2022-01-23
      • 1970-01-01
      • 1970-01-01
      • 2017-07-08
      • 2020-06-05
      • 2017-12-11
      • 2016-05-01
      相关资源
      最近更新 更多