一个简单的脚本,其超时值取决于元素's属性-jQuery
A simple script with timeout value dependent on value in element's attribute - jQuery
我正在尝试运行一个脚本,该脚本在声明的秒数后从DOM中删除一个元素。
脚本应该为多个元素提供服务,这些元素在声明的时间后消失。
要素:
<div class="communique-warning data-closein="2">
You forgot to declare your country!
</div>
<div class="communique-info data-closein="5">
Your action was completed successfully!
</div>
JS:
$('[data-closein]').each(function() {
var after = $(this).data("closein") + '000';
console.log('Time to delete: ' + after);
setTimeout(function() {
$(this).fadeOut('fast');
console.log('rolled up');
$(this).remove();
console.log('removed!');
}, 3000); // <-- time in milliseconds
});
问题:
使用上面的代码,我得到了Uncaught TypeError: Cannot read property 'defaultView' of undefined
错误。
this
上下文似乎在setTimeout内不起作用。这样做的正确语法是什么?我可以用变量
after
代替setTimeout
函数的3000毫秒值吗?
在setTimeout
调用的函数内的$(this)
井引用该函数。您可以简单地在该函数之前为变量指定$(this)
,然后在setTimeout
调用的函数中使用它:
$('[data-closein]').each(function() {
var after = $(this).data("closein") + '000';
console.log('Time to delete: ' + after);
vat $this = $(this);
setTimeout(function() {
$this.fadeOut('fast');
console.log('rolled up');
$this.remove();
console.log('removed!');
}, 3000); // <-- time in milliseconds
});
问题是setTimeout中的这个。setTimeout中的"this"与最初在每个函数上使用它的位置不同。要修复它,您需要保存它或将它绑定到传递给setTimeout的函数。。
$('[data-closein]').each(function() {
var after = $(this).data("closein") + '000';
console.log('Time to delete: ' + after);
var $dataCloseIn = $(this);
setTimeout(function() {
$dataCloseIn.fadeOut('fast');
console.log('rolled up');
$dataCloseIn$.remove();
console.log('removed!');
}, 3000); // <-- time in milliseconds
/* or
var removeDataCloseIn = function() {
$(this).fadeOut('fast');
console.log('rolled up');
$(this).remove();
console.log('removed!');
}.bind(this);
setTimeout(removeDataCloseIn,3000);
*/
});
点击此处了解更多信息https://github.com/getify/You-Dont-Know-JS/blob/master/this%20&%20object%20prototypes/README.md#你不知道js这个——对象原型
相关文章:
- 如何使用jquery/javascript将类添加到不同的元素中,具体取决于当天
- JQuery Mobile单击事件不起作用,具体取决于HTML中的元素位置
- 隐藏元素取决于 if/else 语句的值不起作用
- 使 HTML 元素可见/不可见取决于 HttpServletRequest 参数
- 输入焦点取决于更大的父元素与 jQuery
- jQuery - 进度条和分页,具体取决于显示的元素和枚举数
- 如何使用jQuery将所有HTML元素包装在DIV中,具体取决于这些HTML元素的总高度
- 仅将特定元素添加到 html 正文中,具体取决于 javascript 条件
- 我在表单页面上有一个弹出窗口以及一个隐藏元素,具体取决于用户输入.两者都使用 jquery
- Jquery 返回元素的 .width() 取决于元素的找到方式
- 元素的绝对位置为左或右,具体取决于它所在的位置
- 设置元素的不透明度取决于其他元素以角度向上滚动
- 旋转取决于元素的右或左悬停
- 移除元素取决于它的背景图像
- 插入/更新子元素或插入集合中的完整文档-取决于现有的主元素
- 滚动到元素's偏移量取决于页眉高度
- 将类切换到特定元素取决于URL的哈希值
- jQuery Tablesorter: addParser取决于第th元素的css类
- 动画的持续时间取决于元素的高度
- jQuery左边框取决于元素宽度