在已加载到页面的元素上运行脚本

时间:2014-08-30 03:43:47

标签: javascript jquery html

我正在通过jQuery加载顶部导航:

<script> 
    $(function(){
        $("#top-nav").load("top-nav.html");
    });
</script>   

会加载这样的内容:

<ul class="list-inline text-center navigation">
    <li>
        <a href="one.html">
            one
        </a>
    </li>
    <li>
        <a href="two.html">
            two
        </a>
    </li>
    <li>
        <a href="three.html">
            three
        </a>
    </li>
</ul>

这很有效。我现在正尝试使用此脚本强制显示活动链接:

<script type="text/javascript" charset="utf-8">
    var url = window.location.href.split('/').pop();
    jQuery(function() {
        jQuery('ul a').each(function() {
            if(jQuery(this).attr('href') === url) {
                jQuery(this).parent().addClass('underline-nav');
            }
        });
    });
</script>

然而,它不起作用,因为它找不到one.html,two.html,three.html。我知道这是因为如果我将top-nav.html的内容粘贴到正文中,而不是加载它,这很有效。

以下是我的问题:如何在加载到页面中的元素上运行脚本?

感谢。

2 个答案:

答案 0 :(得分:1)

使用此代码。

<script> 
$(function(){
    var url = window.location.href.split('/').pop();
    $("#top-nav").load("top-nav.html", function(){

    jQuery('ul a').each(function() {
        if(jQuery(this).attr('href') === url) {
            jQuery(this).parent().addClass('underline-nav');
        }

   });
});
});

答案 1 :(得分:0)

使用complete的{​​{1}}回调函数来确保它已加载。

load

文档:http://api.jquery.com/load/

  

如果提供“完整”回调,则在之后执行   已经执行了后处理和HTML插入。

相关问题