[英]Using append() from Jquery outside the HTML document
我試圖在單獨的.JS文件中使用Jquery,因為將所有JavaScript代碼保留在HTML文檔之外會提高加載HTML文檔的性能。
對於此示例,我使用“ index.html”和“ main.js”
以下是index.html:
<html lang="en">
<head>
<meta charset="utf-8">
<title>append demo</title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="testJS/main.js"></script>
</head>
<body>
<p>I would like to say: </p>
<!-- CODE BELOW MUST BE REMOVED FROM THIS DOCUMENT -->
<script>
$( "p" ).append( "<strong>Hello</strong>" );
</script>
</body>
</html>
我想從html剪切代碼並將其插入main.js,但是以下示例對我不起作用:
main.js:
p.append( "<strong>Hello</strong>" );
我也嘗試過此方法,但沒有成功:
$( "p" ).append( "<strong>Hello</strong>" );
我該如何解決這個問題,將JavaScript放入.js文件中又有什么區別?
您需要將代碼添加到dom ready處理程序中,因為否則,在執行代碼時,仍不會將p
元素添加到dom中-這是因為因為main.js
是在標記中的p
元素之前添加的,但是無論如何最安全的選擇是使用dom ready處理程序進行dom操作
jQuery(function($){
$( "p" ).append( "<strong>Hello</strong>" );
})
我建議使用JQuery提供的$( document ).ready()
函數:
$(document).ready(function() {
$("p").append( "<strong>Hello</strong>" );
});
在這里您可以找到更多信息: http : //learn.jquery.com/using-jquery-core/document-ready/
使用外部js時,您必須將代碼包裝在這樣的文檔就緒函數中
$(function(){
$('p').append('<strong>Hello</strong>');
});
*注意- $(function(){
是$(document).ready(function(){
正如Arun P Johny解釋的那樣,問題在於js代碼在其所依賴的DOM元素就緒之前就已在執行。
另一種解決方案是更改外部文件,以便它定義一個函數,然后在html文件的正文末尾調用該函數。
<html lang="en">
<head>
<meta charset="utf-8">
<title>append demo</title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="testJS/main.js"></script>
</head>
<body>
<p>I would like to say: </p>
<script>
writeText();
</script>
</body>
</html>
<!-- main.js -->
function writeText(){
$( "p" ).append( "<strong>Hello</strong>" );
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.