JavaScript DOM 对象到 jQuery 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9489779/
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
JavaScript DOM object to jQuery object
提问by user1238843
How can I convert a JavaScript DOM object to a jQuery object?
如何将 JavaScript DOM 对象转换为 jQuery 对象?
<tr onclick="changeStatus(this)">
function changeStatus(myObject) {
XXX.removeClass();
}
What should I write in place of XXX?
I know I can make a workaround using an id and an id selector, but it is not so elegant.
Is there any way to convert a js DOM object to a jQuery object or using the this
keyword in jQuery?
我应该写什么来代替XXX?我知道我可以使用 id 和 id 选择器来解决这个问题,但它并不是那么优雅。有什么方法可以将js DOM对象转换为jQuery对象或this
在jQuery中使用关键字?
回答by Jasper
var $this = $(myObject);
$this
is a jQuery object. You can create jQuery objects from DOM elements.
$this
是一个 jQuery 对象。您可以从 DOM 元素创建 jQuery 对象。
<tr onclick="changeStatus(this)">
function changeStatus(myObject) {
$(myObject).removeClass();
}
I would like to recommend doing your event binding with jQuery as well:
我还建议您使用 jQuery 进行事件绑定:
<tr class="change-status">
$('.change-status').on('click', function () {
$(this).removeClass( ... );
});
This is nice because now all the JS code is in one place and can be updated (in my opinion) more easily. Note that the class I added to the <tr>
element is not necessary if you want to bind to all <tr>
elements in the DOM.
这很好,因为现在所有的 JS 代码都在一个地方并且可以更容易地更新(在我看来)。请注意,<tr>
如果要绑定到<tr>
DOM 中的所有元素,则不需要我添加到元素中的类。
回答by fullsailor
Simply wrap the pass the DOM object in as the first argument.
简单地将传递的 DOM 对象包装为第一个参数。
$(myObject).removeClass('foo');