2010-06-08 61 views
2

我想在我的html頁面上使用函數,但內容通過ajax傳遞,我如何首先加載腳本然後應用函數?如果將腳本包含在我的<head>中,它將不起作用。另外我怎樣才能使用jQuery .find(),並且應用一個函數或者修改css中已經加載頁面後傳遞的內容?在函數之前加載腳本

+0

你是通過'document.createElement('script')'注入腳本嗎? – Amarghosh 2010-06-08 09:18:34

回答

1

LABjs(http://labjs.com/)有,一個真棒接口。這是一個示例代碼。

<!-- In the head --> 
<script src="lab.js"></script> 
<!-- In the body --> 
<script> 
    $LAB 
    .script("yourscript.js") 
    .wait(function(){ 
      yourfunction(); 
    }); 
</script> 

在上面的例子中,yourfunction();將只腳本yourscript.js已被加載之後被調用。

編輯:在使用.load方法進行ajax調用之後,這就是您的主體腳本的外觀。

<script> 
    $('taggetelmselector').load(your_url, data, function(){ 
     $LAB 
     .script("yourscript.js") 
     .wait(function(){ 
      yourfunction(); 
     }); 
    }); 
</script> 
+0

我希望通過ajax加載搜索結果後加載 – andrei 2010-06-08 10:35:49

+1

儘管您仍然需要使用LABjs,但您需要爲ajax調用添加ajax complete事件處理程序。我將更新示例,假設您正在使用.load()[http://api.jquery.com/load/]方法。 – partoa 2010-06-08 10:53:47

+0

找到了答案: 我用$ .get();結合$ .getScript來自動刷新腳本,這樣他們就可以記住新元素 – andrei 2010-06-08 10:55:17

0

jQuery具有內置於getScript函數中的此功能。

$.getScript('yourscript.js', yourfunction); 
相關問題