首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在一段时间后使用$(this)元素做一些事情

在一段时间后使用$(this)元素做一些事情
EN

Stack Overflow用户
提问于 2018-08-26 21:18:10
回答 2查看 42关注 0票数 0

我有输入为“datapicker”的表单...令人恼火的是,我看不到输入错误,因为输入具有"readonly“属性。

所以我有这样的代码:

代码语言:javascript
复制
$('p.send-app-btn input[type="submit"]').on('click', function(){
$('input').each(function(){
if ( $(this).is('[readonly]') && $(this).prop('required') && !$(this).val()) {
    $(this).removeAttr('readonly');

if($(this).is(':focus') && $(this).hasClass('hasDatepicker')){
  setTimeout(function () {
$(this).attr('readonly','readonly');
}, 1500);  
}
}
})
});

而且它工作得很好,因为它从$(this)输入中删除了属性"readonly“,并且显示了输入错误。但我希望在1.5秒之后(在错误消失之后),聚焦的输入将再次成为“只读”。

但是这部分代码无法工作,因为我无法捕获$(this) --我如何才能用另一种方式来实现呢?

代码语言:javascript
复制
if($(this).is(':focus') && $(this).hasClass('hasDatepicker')){
      setTimeout(function () {
    $(this).attr('readonly','readonly');
    }, 1500);  
    }

我希望这是清楚的。:)

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-08-26 21:50:55

通过help @Ulrich-dohou,我找到了解决方案:

代码语言:javascript
复制
$('input').each(function(){
if ( $(this).is('[readonly]') && $(this).prop('required') && !$(this).val()) {
    $(this).removeAttr('readonly');
    setTimeout(() => {
$(this).attr('readonly','readonly');
},1500)
}
})

只是我的代码在按下提交按钮的瞬间检查了$(this).is(':focus')。这是足够晚一点检查它(足够1秒),它工作得很好。感谢您的回答!

票数 0
EN

Stack Overflow用户

发布于 2018-08-26 21:27:14

您可以将this作为参数传递给setTimeout函数-

代码语言:javascript
复制
setTimeout(function(_this) {
  _this.attr('readonly','readonly');
}, 1500, $(this)); 
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52026630

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档