【问题标题】:jQuery input value undefined or white text [duplicate]jQuery输入值未定义或白色文本[重复]
【发布时间】:2019-05-01 16:24:08
【问题描述】:

这个问题之前大概已经被问过一千遍了,但是不知道是不是因为SEO的原因,一直没有找到合适的解决方案。我在 Chrome 中得到未定义或空白文本。

$('input[type="text"]').on('input', (a, b) => {
    console.log(this.value);
});

这在我也尝试过的控制台中不断返回 undefined:

$('input[type="text"]').on('input', (a, b) => {
       console.log(b);
    });

$('input[type="text"]').on('input', (a, b) => {
       console.log($(this).val());
    });

$('input[type="text"]').on('input', (a, b) => {
       console.log(a.value);
    });

$('input[type="text"]').on('input', (a, b) => {
       console.log(b.value);
    });

任何想法都将不胜感激。

【问题讨论】:

    标签: javascript jquery dom-events jquery-events


    【解决方案1】:

    this 关键字对我们不起作用,因为您使用的是 es6 箭头函数格式,这会改变上下文,请使用 e.target 代替它。

    看看What does “this” refer to in arrow functions in ES6?

    $('input[type="text"]').on('input', (e) => {
      console.log(e.target.value);
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <input type="text" value="test">

    【讨论】:

    • 哇,解决了!我不知道胖箭头改变了返回值的工作方式!
    • 'e.target.value.test' 为什么这是不可能的?
    • values 属性没有test 属性,你到底想得到什么?
    • 应该是new RegExp("your_regex").test(e.target.value);
    【解决方案2】:

    这是因为您使用的箭头函数的作用域与普通函数不同。

    通常您可以用常规函数表达式替换箭头函数并使用$(this) 或使用事件处理程序中的目标对象来获取输入的值

    $('input[type="text"]').on('input', function(a, b) {
      console.log($(this).val());
    });
    
    $('input[type="text"]').on('input', (a, b) => {
      console.log(a.target.value);
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <input type='text'>

    【讨论】:

    • 这与另一个答案相同:|
    • @MoshFeu 好好看看
    • 你现在添加了常规的function 方法。很好。
    • 那是在您第一次发表评论之前添加的。请从修订历史中验证它
    • 当你是对的,你是对的:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-05
    • 2017-12-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-21
    • 2017-11-12
    • 2010-11-22
    相关资源
    最近更新 更多