简体   繁体   English

使用jQuery在div中加载页面

[英]Load page in div using jQuery

This jQuery code loads a specific page within a div (this works): 这个jQuery代码在div中加载一个特定的页面(这个工作):

    <script type="text/javascript">
        $(document).ready(function() {

            $("#button2").on("click", function(){  
                $("#loader").load($("#button2").attr("page"));
                return false;
            });
        });
    </script>

Also, I have 2 links with an attribute "page" indicating the html file to be loaded in the div: 另外,我有2个属性“page”的链接,表示要在div中加载的html文件:

<li><a href="#" title="" id="button2" page="page1.html">Link 1</a></li>
<li><a href="#" title="" id="button2" page="page2.html">Link 2</a></li>

This is the div where the page is loaded: 这是加载页面的div:

<div id="loader"></div>

The problem is that only loads "page1.html" when I click on the first link. 问题是当我点击第一个链接时只加载“page1.html”。 If I click on the second link does not load "page2.html". 如果我点击第二个链接不加载“page2.html”。

I think it may be a problem of the id attribute of link "button2" on repeat maybe something happens. 我认为这可能是链接“button2”的id属性的问题,重复可能会发生一些事情。

What am I doing wrong? 我究竟做错了什么?

Thank you! 谢谢!

You must not use same ids for elements. 您不得对元素使用相同的ID。 Each id attribute must be unique (according to HTML4.01 and HTML5 specs). 每个id属性必须是唯一的(根据HTML4.01HTML5规范)。

It would be better to use a class to identify these buttons instead, like this: 最好使用类来识别这些按钮,如下所示:

<script type="text/javascript">
    $(document).ready(function() {

        $(".buttons").on("click", function(){  
            $("#loader").load($(this).attr("page"));
            return false;
        });
    });
</script>

and the button's HTML: 和按钮的HTML:

<li><a href="#" title="" class="buttons" page="page1.html">Link 1</a></li>
<li><a href="#" title="" class="buttons" page="page2.html">Link 2</a></li>

"What am I doing wrong?" “我究竟做错了什么?”

You are using duplicate ID's, which is forbidden in HTML. 您正在使用重复的ID,这在HTML中是禁止的。 Use a class name or an element selector instead. 请改用类名或元素选择器。 You can refer to the currently clicked button inside the event handler by $(this) : 你可以通过$(this)来引用事件处理程序中当前单击的按钮:

<li><a href="#" title="" class="button" page="page1.html">Link 1</a></li>
<li><a href="#" title="" class="button" page="page2.html">Link 2</a></li>

$(".button2").on("click", function(){  
    $("#loader").load($(this).attr("page"));
    return false;
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM