从一个HTML中导入文本,并使用javascript将其插入另一个HTML


Importing text from one HTML and inserting it into another with javascript

我正试图在我正在设计的网站的主页上制作一个最新新闻风格的部分,我想从我的文章页面中提取标题,并将其用作主页上最新新闻部分的标题,我主页上的最新新闻节如下所示:

<body onload="insertText()">
<section class="latest">
                <h1 class="latesth" id="test"> Latest News: </h1>
                        <section class="title" onclick="changeImagea()">
                            <h3 id="h1" > Mcilroy Wins US Open </h3>
                            <p> He wins by three shots in horrendous condition, <u>click here</u> to read more </p>
                        </section>
                        <section class="title" onclick="changeImageb()">
                            <h3> Tiger Wins Masters </h3>
                            <p> He wins by three shots in horrendous condition, <u>click here</u> to read more </p>
                        </section>
                        <section class="titlebottom" onclick="changeImagec()">
                            <h3> Mcilroy Wins US Open </h3>
                            <p> He wins by three shots in horrendous condition, <u>click here</u> to read more </p>
                        </section>
                </section>

到目前为止,我的javascript看起来是这样的,它在一个外部javascript文件中:

 function insertText () {
    var x = document.getElementById('ahead').innerHTML;
    document.getElementById('h1').innerHTML = x;
    }

最后,article.php页面id中要抓取并插入主页的文本如下所示:

<section>
<h1 id="ahead"> hello </h1>
</section>

谢谢你的帮助,希望我是清白的。

我建议使用jQuery,它将为您节省大量时间和问题。

如果#ahead元素在另一个页面中,您可以执行以下操作:

$('h1').load('/foo #ahead');