javascript getElementsByTagName 与 jQuery
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21126769/
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
getElementsByTagName vs jQuery
提问by Jordan
What would the version of this be in jquery?
这个版本在 jquery 中是什么?
document.getElementsByTagName("pre")[0].innerHTML;
I need help converting this in order to fit into my $.get
request:
我需要帮助转换它以符合我的$.get
要求:
$.get(
link,
function(data) {
var res = $(data).find("pre").html();
console.log(res);
}
);
回答by Cilan
The exact[JQuery equivalent] would be $('pre').eq(0).html()
. The sortof-ish mix with non-JQuery would be $('pre')[0].innerHTML
的确切[JQuery的等效]将是$('pre').eq(0).html()
。与非 JQuery 的混合将是$('pre')[0].innerHTML
How's it work?
它如何运作?
$('pre')
returns an Object with all elements with a tag name of pre
$('pre')
返回一个包含所有元素的对象,其标签名称为 pre
.eq(0)
gets the first element in the array.
.eq(0)
获取数组中的第一个元素。
DEMO
演示
Since you're getting the first item, $('pre').first().html()
also works.
由于您获得了第一项,因此$('pre').first().html()
也有效。
DEMO
演示
Another thing that works would be just $('pre').html()
(Credit to RobG)
另一件有效的事情就是$('pre').html()
(归功于 RobG)
DEMO
演示
Please note that JQuery's html
method is not identical to a browser's innerHTML
property but it's the JQuery equivalent (Credit to RobG).
请注意,JQuery 的html
方法与浏览器的innerHTML
属性不同,但它与 JQuery 等效(归功于 RobG)。
回答by bearfriend
Here it is in jQuery:
这是在 jQuery 中:
$('pre').first().html()
$('pre').first().html()
回答by Wayne
Simply specify the element name in the selector:
只需在选择器中指定元素名称:
$("pre").html()
It's not necessary to explicitly select the first element. From the API docs:
没有必要显式选择第一个元素。来自API 文档:
If the selector expression matches more than one element, only the first match will have its HTML content returned
如果选择器表达式匹配多个元素,则只有第一个匹配项将返回其 HTML 内容
回答by Wayne
If you only need one element, give the element and ID and pull it by ID
如果你只需要一个元素,给元素和ID并按ID拉
document.getElementById("ID")