在非当前 HTML 文档上使用 getElementById()
本质上,我想从服务器上的文档中提取 div 标签内的文本,并将其放置在当前文档中。解释一下原因:我想从“新闻文章”中提取标题,将其用作该文章链接的文本。
例如,目标 HTML 中有标签:
<div id='news-header'>Big Day in Wonderland</div>
因此,在我当前的文档中,我想使用 javascript 将锚标记内的文本设置为该标题,即:
<a href='index.php?link=to_page'>Big Day in Wonderland</a>
我无法弄清楚如何访问非当前文档在JS中。
预先感谢您的帮助。
添加:Firefox 风格问题(请参阅下面的评论)。
Essentially, I want to pull text within a div tag from a document on my server to place it in the current document. To explain the reason: I want to pull a headline from a "news article" to use it as the text for a link to that article.
For example, within the target HTML is the tag:
<div id='news-header'>Big Day in Wonderland</div>
So in my current document I want to use javascript to set the text within my anchor tags to that headline, i.e.:
<a href='index.php?link=to_page'>Big Day in Wonderland</a>
I'm having trouble figuring out how to access the non-current document in JS.
Thanks in advance for your help.
ADDED: Firefox style issue (see comment below).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我不确定你从哪里获得 HTML,但是假设你已经将它放在字符串中,你可以 创建您自己的文档,将 HTML 填充到其中,然后使用标准的
getElementById
拉出您想要的片段。例如:实时版本:http://jsfiddle.net/ambigously/ZZq2z/1/
I'm not sure where you're getting your HTML but, assuming you already have it in a string, you could create a document of your own, stuff your HTML into it, and then use the standard
getElementById
to pull out the piece you want. For example:Live version: http://jsfiddle.net/ambiguous/ZZq2z/1/
通常,我会尝试仅使用用户指定的工具来解决问题;但如果您使用的是 javascript,那么确实没有充分的理由不只使用 jQuery。
那里的那个小功能可以帮助您动态更新所有链接的文本。如果您有多个,则可以将其放入
$('a').each()
循环中,然后就到此为止了。更新以根据条件支持多个链接:
选择器确保仅处理存在属性“linked_div”的链接。
Normally, I would try to solve an issue only with the tools specified by the user; but if you are using javascript, there really is no good reason not to just use jQuery.
That little function up there can help you update all your link's text dynamically. If you have more than one, you can just put it in a
$('a').each()
loop and call it a day.update to support multiple links on condition:
The selector makes sure that only the links with the existence of the attribute 'linked_div' will be processed.
正如 QuentinUK 提到的,您需要将远程文档的内容拉取到当前 DOM 中。我推荐类似 jQuery 的 .load() 方法
You need to pull the content of the remote document into the current DOM, as QuentinUK mentioned. I'd recommend something like jQuery's .load() method