jQuery内容加载到加载页面上的div

时间:2014-03-18 22:44:02

标签: jquery html5 twitter-bootstrap

我有一个学位的工作脚本。问题是最后一个内容没有加载到目标div区域,但它加载到整个页面。

第一页是登陆页面,很好:

<div class="container">
    <div class="row">
        <div class="col-md-2">
            <ul class="nav nav-pills nav-stacked">
                <li><a class="dashnav" href="content/company.html">Company</a>
                </li>
                <li><a class="dashnav" href="content/buyer.html">Buyer</a>
                </li>
                <li><a class="dashnav" href="content/settings.html">Settings</a>
                </li>
            </ul>
        </div>
        <div class="col-md-10">
            <div id="content"></div>
        </div>
    </div>
</div>
<!-- /container -->

这是jQuery。它可以很好地加载菜单,但不会将最后一个内容加载到dashcontent div中:

$(document).ready(function () {
    // select where the content is to go and what content is be loaded

    $('#content').load($('.dashnav:first').attr('href'));

    //click button from first dashnav
    $('.dashnav').click(function () {

        //What Link has been clicked
        var href = $(this).attr('href');

        //load content from that link
        $('#content').load(href, function () {

            //once the content is loaded
            $('#dashcontent').load($('.companynav:first').attr('href'));

            //click on link from newly loaded page
            $('.companynav').click(function () {

                //What Link has been clicked
                var href = $(this).attr('href');

                //load that content
                $('#dashcontent').load(href);

            });

        });

        return false; //stops the page redirect

    });

});

第二页:

<ul class="nav nav-pills companynav">
    <li><a href="content/dashboard/basic.html">Basic</a>
    </li>
    <li><a href="content/dashboard/factory.html">Factory</a>
    </li>
    <li><a href="content/dashboard/company_bio.html">Company Bio</a>
    </li>
</ul>
<div class="col-md-10">
    <div id="dashcontent"></div>
</div>

最终结果应该将basic.html加载到dashcontent区域,但它不会:

<h1>Basic Profile</h1>
<p>Edit your Company profile</p>

任何帮助都会很棒。

2 个答案:

答案 0 :(得分:0)

尝试在.companynav上的第二个(嵌套)点击处理程序中返回false:

....
//click on link from newly loaded page
$('.companynav').click(function(){

    //What Link has been clicked
    var href = $(this).attr('href'); 

    //load that content
    $('#dashcontent').load(href);

  return false;

 });
....

答案 1 :(得分:0)

听起来你应该使用jQuery的.on()方法进行事件委托:http://api.jquery.com/on/#direct-and-delegated-events

另外,如果我是你的回调较少而是使用promises,我会清理代码。

对于你当前的问题,它看起来像这样:

$('#dashcontent').load($('.companynav:first').attr('href'));

应该是

$('#dashcontent').load($('.companynav a:first').attr('href'));

预览:http://plnkr.co/edit/SJzK17sw5YVLrQvuI7Gb?p=preview