[英]Adding content to a div from javascript
我想在HTML頁面上加載包含div內容的腳本。 我知道這是可能的,但是我正在努力了解如何做到這一點。 這是我的html:
<html>
<body>
<script src="script.js"> </script>
<div id="helloWorld"> </div>
</body>
</html>
要使html頁面顯示某些內容,script.js必須是什么? 我在想這樣的事情(我知道這是錯誤的,我是javascript的初學者。
function showText()
{
$("#helloWorld").html("<p> Hello World! </p>")
$("#helloWorld").show();
}
showText()
有人可以告訴我我是否在正確的軌道上,以及如何解決此問題? 謝謝山姆
您的代碼是jQuery:
$("#helloWorld").html("<p> Hello World! </p>")
$("#helloWorld").show();
而且您不需要$("#helloWorld").show();
。
在純JavaScript中,
function showText()
{
document.getElementById("helloWorld").innerHTML="<p> Hello World! </p>";
}
showText()
但是切記在div中加載div之后調用showText()
! (例如,在</body>
標記之前調用它)。
然后,
<html>
<head>
...
<script type="text/javascript" src="script.js"></script>
...
</head>
<body>
...
<script type="text/javascript">
showText();
</script>
</body>
</html>
和script.js:
function showText(){
document.getElementById("helloWorld").innerHTML="<p> Hello World! </p>";
}
我認為它沒有任何作用(我認為),因為您的script標簽位於div本身之前。 如果您使用的是JQuery,則應將初始代碼放入ready函數中,具體情況如下:
$(document).ready(function(){
showText();
});
腳本加載后,HTML元素“ #helloWorld
”仍然不存在。
使用$(document).ready
像這樣:
function showText() {
$("#helloWorld").html("<p> Hello World! </p>")
$("#helloWorld").show();
}
$(document).ready(function() {
showText();
});
您嘗試使用的語法需要JQuery。 您可以在http://jquery.com/下載最新的JQuery庫。
然后,您可以使用以下命令向div添加文本:
$(document).ready(function(){
var showText = function(){
$("#helloWorld").html("<p> Hello World! </p>")
$("#helloWorld").show();
};
showText();
});
編輯:我已經在(document)的開頭添加了$字符,並且也不必在div上具有.show()
函數,因為它已經可見。 但是,如果確實將div的顯示設置為none,則應使用.show()
來顯示div。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.