在jquery加载函数之前单击每个菜单的元素调用相关的js库

我尝试将带有jquery load函数的内容加载到index.html的内容区域。 我成功了但是我的js没有用。 所以我想在每次单击菜单元素时调用它们。 可能吗?

点击这里查看页面

菜单:

加载function:

 $(document).ready(function() { $('#content').load($('#navmenu li a:last').attr('href')); var hash = window.location.hash.substr(1); var href = $('#navmenu li a').each(function(){ var href = $(this).attr('href'); if(hash==href.substr(0,href.length-5)){ var toLoad = hash+'.html #content'; $('#content').load(toLoad) } }); $('#navmenu li a').click(function(){ var toLoad = $(this).attr('href')+' #content'; $('#content').hide('slow',loadContent); $('#load').remove(); window.location.hash = $(this).attr('href').substr(0,$(this).attr('href').length-5); function loadContent() { $('#content').load(toLoad,'',showNewContent()) } function showNewContent() { $('#content').show('slow',hideLoader()); } function hideLoader() { $('#load').fadeOut('slow'); } return false; }); }); 

听起来像你正试图动态加载HTML和JavaScript。 当您使用动态加载内容的任何方法(包括.load() ,它只加载静态内容,这意味着它不会解析并执行您尝试加载的任何JavaScript。

此外,除非您使用eval ,否则在页面加载后没有动态加载和执行javascript的跨浏览器方式,这是不推荐的。

我建议在主index.html页面中包含所有的javascript,然后动态地从其他页面加载html,然后调用该动态内容所需的javascript函数。

编辑:你需要在html加载完成后调用你的库的javascript函数。 所以你需要为.load()函数提供一个回调:

 $('#content').load( $(this).attr('href'), function () { /* javascript calls here */ } ); 

我不确定这是否会导致您的问题,但对于您尝试加载到#content div的所有四个url,内容都以

开头。 您应该从内容中删除它,因为它已加载到

。 否则,你最终得到:

 
...

请注意, .load()函数不会替换它所调用的元素,它会将返回的html插入到它的正文中。

这是我在加载content/aboutme.html内容后检查页面时在Firefox中看到的content/aboutme.html

在此处输入图像描述

此外,如果要加载的内容需要使用动态行为进行检测,则可能需要在将其插入DOM后对其进行检测。 在这种情况下,您需要将回调函数传递给.load()函数。

 $('#content').load(url, function(responseText, textStatus) { if (textStatus == "success") { // Instrument the dynamic behavior of the elements just inserted into // the #content div here. carouselfn(); } });