在非当前HTML文档上使用getElementById() [英] Use getElementById() on non-current HTML document

查看:94
本文介绍了在非当前HTML文档上使用getElementById()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我想从服务器上的文档中提取div标记中的文本,以将其放置在当前文档中.解释原因:我想从新闻文章"中提取标题,以将其用作指向该文章的链接的文本.

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.

例如,目标HTML中包含标记:

For example, within the target HTML is the tag:

<div id='news-header'>Big Day in Wonderland</div>

因此,在当前文档中,我想使用javascript将锚定标记中的文本设置为该标题,即:

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>

我在弄清楚如何访问JS中的非当前文档时遇到了麻烦.

I'm having trouble figuring out how to access the non-current document in JS.

预先感谢您的帮助.

已添加:Firefox样式问题(请参见下面的评论).

ADDED: Firefox style issue (see comment below).

推荐答案

通常,我只会尝试使用用户指定的工具来解决问题;但是,如果您使用的是JavaScript,则确实没有充分的理由不只使用jQuery.

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.

<a id='mylink' href='url_of_new_article' linked_div='id_of_title'></a>

$(function() {
    var a = $('#mylink');
    a.load(a.attr('href') + ' #' + a.attr('linked_div'));
});

那里的那个小功能可以帮助您动态更新所有链接的文本.如果您有多个,则可以将其放在$('a').each()循环中,然后将其命名为一天.

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:

$(function() {
    $('a[linked_div]').each(function() {
        var a = $(this);
        a.load(a.attr('href') + ' #' + a.attr('linked_div'));
     });
});

选择器确保仅处理具有属性"linked_div"的链接.

The selector makes sure that only the links with the existence of the attribute 'linked_div' will be processed.

这篇关于在非当前HTML文档上使用getElementById()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆