javascript JQuery 中 document.getElementbyId 的等价物是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15035992/
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-10-26 23:15:08  来源:igfitidea点击:

What is the equivalent of document.getElementbyId in JQuery?

javascriptjquery

提问by TIMEX

map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);

But this does not work:

但这不起作用:

map = new google.maps.Map($('#map_canvas'), mapOptions);

I am looking for something like...

我正在寻找类似...

$('#map_canvas').toElementBlahblah?

回答by Fabrício Matté

.get(index)

.get(index)

$('#map_canvas').get(0)
$('#map_canvas')[0]


Though, document.getElementByIdobviously has better performance - it is the method used internally by the jQuery core when querying the DOM for a single ID selector.

但是,document.getElementById显然具有更好的性能 - 这是 jQuery 核心在查询 DOM 以获取单个 ID 选择器时在内部使用的方法。

So then you're building a jQuery object just to discard it afterwards. Up to you whether to save some bytes in the bandwidth or microseconds in execution time.

那么你正在构建一个 jQuery 对象只是为了在之后丢弃它。由您决定是在带宽中节省一些字节还是在执行时间中节省微秒。

Not much difference, honestly. I use the jQuery version when performance is not concerned and I'm lazy to type document.getElementById, though vanilla JS is a bit more logical in this case.

没有太大区别,老实说。我在不关心性能时使用 jQuery 版本,而且我懒得输入document.getElementById,尽管在这种情况下 vanilla JS 更合乎逻辑。

回答by Bergi

You can use the .get()method:

您可以使用以下.get()方法

 $('#map_canvas').get(0);
 $('#map_canvas')[0]; // or direct property access

However, I can see no reason not to use document.getElementById.

但是,我看不出没有理由不使用document.getElementById.