仅使用 javascript 获取网站的正文元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26067590/
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
Get body element of site using only javascript
提问by Zak
I would like to retrieve the following sites body content http://sports.espn.go.com/nhl/bottomline/scores?nhl_s_left1and store it in a string, i know and am successful at retrieving this using php, however i want to restrict to using only javascript, is there a way just to take the string in the site and copy it and store it in a var?
我想检索以下网站正文内容http://sports.espn.go.com/nhl/bottomline/scores?nhl_s_left1并将其存储在一个字符串中,我知道并且成功地使用 php 检索了它,但是我想要为了限制只使用 javascript,有没有办法在站点中获取字符串并将其复制并存储在 var 中?
回答by Lalit Mohan
Although the @Brendan's answer is accepted and correct.
尽管@Brendan 的回答被接受并且是正确的。
It is simple, short and faster enough to get a body element using
它简单、简短且足够快,可以使用
document.body;
It does the same as we can do with document.getElementsByTagName('body')[0];, and it should be in the list of answers.
它和我们可以做的一样document.getElementsByTagName('body')[0];,它应该在答案列表中。
回答by Brendan
Try this:
尝试这个:
<script>
window.onload = function get_body() {
body = document.getElementsByTagName('body')[0];
}
</script>
Allow me to explain. The window.onloadis so that the HTML loads before the script is executed. Even though there is only one body tag this is the method i use^. Basically, it finds the "first" body tag there is, then I tell it to just get the body element itself and not all the other attributes and child nodes that go along with it using an index of [0]. If you want everything to do with the body tag then lose the index of 0. Hope this Helps!
请允许我解释一下。这window.onload是为了在执行脚本之前加载 HTML。即使只有一个 body 标签,这也是我使用的方法^。基本上,它会找到存在的“第一个”body 标签,然后我告诉它只获取 body 元素本身,而不是使用[0]. 如果你想要与 body 标签有关的所有事情,那么失去 0 的索引。希望这有帮助!

