javascript Internet Explorer 中的 jQuery this.remove() -vs.- $('#id').remove() (IE 9+)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24276146/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery this.remove() -vs.- $('#id').remove() in Internet Explorer (IE 9+)
提问by pemoke
Why is it that this.remove()
doesn't work in IE9+?
为什么它this.remove()
在 IE9+ 中不起作用?
<input type="button" value="Next1" id="nextButton1">
<br>
<input type="button" value="Next2" id="nextButton2">
$('#nextButton1').on('click', function() {
this.remove(); // works in all browsers but IE9+
});
$('#nextButton2').on('click', function() {
$('#nextButton2').remove(); //works in all browsers
});
采纳答案by PeterKA
That's because you're using the ChildNode.remove()
method which is not supported by all browsers.
那是因为您使用的ChildNode.remove()
方法并非所有浏览器都支持。
this ---> refers to a node. //WARNING: This is an experimental technology
jQuery's .remove()
method, however is cross-browser and so to use it you have to wrap this
in $(...)
like this:
jQuery的.remove()
方法,不过是跨浏览器的,因此使用它,你必须包装this
在$(...)
这样的:
$(this).remove();
ChildNode.remove() Browser Compatibility
this.remove()
is supported by the following desktop browsers:
this.remove()
以下桌面浏览器支持:
- Chrome 23+
- Firefox 23+
- Opera 10+
- Safari 7+
回答by Joseph Silber
Wrap this
in jQuery:
包裹this
在 jQuery 中:
$('#nextButton1').on('click', function() {
$(this).remove();
});
回答by Alex W
You asked why, so here's why:
你问为什么,所以这里是为什么:
Within the context of a jQuery event handler, this
refers to the DOM element reference that jQuery stores for the element that you are currently handling events for. Because the .remove()
function you are intending to use is a jQuery member function, and not a native DOM browser function, it does not work as expected.
在 jQuery 事件处理程序的上下文中,this
指的是 jQuery 为您当前正在为其处理事件的元素存储的 DOM 元素引用。由于.remove()
您打算使用的函数是 jQuery成员函数,而不是本机 DOM 浏览器函数,因此它无法按预期工作。
However, if you wrap the DOM reference inside of $()
or jQuery()
, so it becomes $(this)
instead of this
, the $
or jQuery
function takes the DOM reference as a parameter and returns a jQuery reference, which is then capable of having jQuery member functions invoked on it.
但是,如果您将 DOM 引用包装在$()
or 中jQuery()
,那么它变成了$(this)
而不是this
,$
orjQuery
函数将 DOM 引用作为参数并返回一个 jQuery 引用,然后可以在其上调用 jQuery 成员函数。
You can always pass your DOM references to jQuery and get jQuery references back
您始终可以将 DOM 引用传递给 jQuery 并返回 jQuery 引用
E.g.
例如
var test = document.getElementById('test');
$(test).remove();