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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 10:52:56  来源:igfitidea点击:

JavaScript DOM object to jQuery object

domjquery

提问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 thiskeyword in jQuery?

我应该写什么来代替XXX?我知道我可以使用 id 和 id 选择器来解决这个问题,但它并不是那么优雅。有什么方法可以将js DOM对象转换为jQuery对象或this在jQuery中使用关键字?

回答by Jasper

var $this = $(myObject);

$thisis 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');