gpt4 book ai didi

javascript - jQuery - 组合 .hide() 和 .remove()

转载 作者:行者123 更新时间:2023-11-30 09:56:24 25 4
gpt4 key购买 nike

我想定义一个函数来x 毫秒后删除元素

jQuery.fn.extend({
remove: function(x) {
this.hide(x);

//this line won't work
//setTimeout(function(){ this.remove() }, x);
}
});

$("button").click(function() {
$("p").remove(600);
});
p {
background: yellow;
margin: 6px 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div>
<p>Hello</p>
how are
<p>you?</p>
</div>
<button>remove</button>

点击按钮后,html如下所示:

<div>
<p style="display: none;">Hello</p>
how are
<p style="display: none;">you?</p>
</div>
<button>remove</button>

我的问题是:行:setTimeout(function(){ this.remove() }, x); 不起作用。我认为编译器不明白 this 是什么意思?

你能告诉我在 setTimeout 中调用 remove() 函数的想法吗?

最佳答案

setTimeout 中的

this 指的是 window 对象。

使用 hide() 的完整回调

A function to call once the animation is complete, called once per matched element.

this.hide(x, function() {
this.remove();
});

jQuery.fn.extend({
remove: function(x) {
this.hide(x, function() {
this.remove();
});
}
});

$("button").click(function() {
$("p").remove(600);
});
p {
background: yellow;
margin: 6px 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div>
<p>Hello</p>
how are
<p>you?</p>
</div>
<button>remove</button>

关于javascript - jQuery - 组合 .hide() 和 .remove(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33731532/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com