【问题标题】:Displaying div from other html file on button click在按钮单击时显示来自其他 html 文件的 div
【发布时间】:2013-06-14 19:12:30
【问题描述】:

我有this code

<!DOCTYPE html>
<body>
    <div id=div1 style="display:block;">
        <p id="intro">Hello World!</p>
        <p>This example demonstrates the <b>getElementById</b> method!</p>
    </div>
    <div id=div2 style="display:none;">
        <p id="intro">Hello World again!</p>
        <p>This example demonstrates the <b>getElementById</b> method!</p>
    </div>
    <button type="button" onclick="func()">Change div</button>
    <script>
        function func() {
            x = document.getElementById("div1");
            x.style.display = "none";
            x1 = document.getElementById("div2");
            x1.style.display = "block";
        }
    </script>
</body>

它基本上在按钮单击时显示 div2。

当 div2 和 div1 在同一个文件中时,这可以正常工作。我希望 div2 位于不同的文件中,并在我们单击按钮而不更改 url 时显示。

实现此目的的一种方法是使用 iframe 并在单击按钮时更改 iframe 的 url(其中 div2 所在的位置)。

还有其他方法可以实现吗?

我对 html 和 javascript 非常陌生,因此对答案的解释将有很大帮助。谢谢!

【问题讨论】:

  • 可以使用jQuery加载api.jquery.com/load
  • @algorhythm 是否可以仅使用 PHP 而不使用 jQuery 或 AJAX 来完成,正如其他人所建议的那样,如果是的话,而不是关于如何实现这一点的小代码会有所帮助。我知道一些基本的 php,但我完全不知道 AJAX 和 jQuery。如果这只能通过使用 PHP 来完成,那么我想采用这种方法。谢谢!
  • @nav_jan 看看我的答案!

标签: javascript html


【解决方案1】:

如果您不想使用 iframe,则需要使用 AJAX 来执行此操作。见http://en.wikipedia.org/wiki/Ajax_(programming)

【讨论】:

    【解决方案2】:

    对于您希望在页面上动态发生而不加载整个页面的这些类型的事情,您需要使用 AJAX。

    下面这段代码可以帮助你理解一些通过 jQuery 使用 AJAX 的非常基本的技术:

    $(document).ready(function(){
        $("button").click(function(){
            alert('Load was performed.');
            $.get('target_file.html', function(data) {
                $('div').html(data);
                alert('Load was performed.');
            });
        });
    });
    

    更具体地说,您可以像这样从目标文件中找到&lt;div&gt;

    $("div").html(data.find("#div_id"));
    

    还有一件事。如果你想使用 PHP,你可以在这里看到这篇文章:

    php: Get html source code with cURL

    【讨论】:

    • stackoverflow.com/questions/3592270/… 如何解决我的问题,请详细说明。谢谢!
    • 这告诉您如何获取文件的源代码,然后您可以在单击按钮时打印出该 div。
    • 在接受答案之前我必须先尝试一下。我将尝试了解 curl。我会尝试发布代码,然后接受您的回答,但可能需要几天时间。虽然赞成。感谢您的指导。
    猜你喜欢
    • 1970-01-01
    • 2017-09-22
    • 1970-01-01
    • 2016-07-03
    • 2021-12-03
    • 1970-01-01
    • 2014-05-03
    • 2012-06-02
    • 2013-01-16
    相关资源
    最近更新 更多