Javascript 对已加载到页面中的元素运行脚本

Javascript 对已加载到页面中的元素运行脚本,javascript,jquery,html,Javascript,Jquery,Html,我正在通过jQuery加载顶部导航: <script> $(function(){ $("#top-nav").load("top-nav.html"); }); </script> $(函数(){ $(“#top nav”).load(“top nav.html”); }); 将加载如下内容: <ul class="list-inline text-center navigation"> <li&g

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

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

$(函数(){
$(“#top nav”).load(“top nav.html”);
});
将加载如下内容:

<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>

var url=window.location.href.split('/').pop();
jQuery(函数(){
jQuery('ula')。每个(函数(){
if(jQuery(this.attr('href')==url){
jQuery(this.parent().addClass('underline-nav');
}
});
});
但是,它不起作用,因为它找不到one.html、two.html、three.html。我知道这一点,因为如果我将top-nav.html的内容粘贴到主体中,而不是加载它,这将非常有效

我的问题是:如何对加载到页面中的元素运行脚本


谢谢。

使用
load
complete
回调函数确保它已加载

$("#top-nav").load("top-nav.html", function(){
    //check the loaded elements
});
文件:

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

使用此代码

<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');
        }

   });
});
});

$(函数(){
var url=window.location.href.split('/').pop();
$(“#top nav”).load(“top nav.html”,function(){
jQuery('ula')。每个(函数(){
if(jQuery(this.attr('href')==url){
jQuery(this.parent().addClass('underline-nav');
}
});
});
});

.load的回调函数中执行它。