javascript - 为什么 'this' 未定义?

标签 javascript jquery blur

我有一个名为#question_title 的输入。我想对 Blur 事件运行 if 语句。当我尝试检查长度时,它返回为未定义。知道为什么“this”在这里不起作用吗?

JS

$('#question_title').on('blur', function(){
    console.log('this.length = ' + this.length);
    if ( this.length > 1 ) {
        // do something fabulous
    }
});

HTML

<div class="form-group question-title-wrap">
    <label for="question_title">What is your question?</label>
    <input type="text" class="form-control" id="question_title">
</div>

最佳答案

this 指的是元素本身,而不是它的值,因此会出现错误 undefined,因为元素上没有这样的属性 (length)输入元素。

如果您使用this.value.length,您将获得该值及其长度。

$('#question_title').on('blur', function(){
    console.log('this.value.length = ' + this.value.length);
    if ( this.value.length > 1 ) {
        // do something fabulous
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group question-title-wrap">
    <label for="question_title">What is your question?</label>
    <input type="text" class="form-control" id="question_title">
</div>

关于javascript - 为什么 'this' 未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41988598/

相关文章:

javascript - 在 Javascript/jQuery 中确定字符串的像素长度?

javascript - 更改对象子元素的颜色或位置

javascript - 如何重定向页面,等到完全加载然后查询

javascript - Bootbox 不显示弹出模式

video - 如何压缩具有均匀模糊的视频是压缩的唯一副作用?

javascript - DataTable Editor Dependent() - 根据第一个选定的值仅显示/隐藏某些值

javascript - 如何将 iframe 的 src 设置为同一页面(使用不同的 anchor )

javascript - 数据表修改过滤器html

xaml - 在 Windows Phone 应用程序中添加模糊背景

背景图像上的 CSS 模糊,但内容上没有