这是一个基本程序,我不明白为什么它不起作用:
对象类,houseObject.js:
var string;
function createSentence(paragraph){
this.string = paragraph;
}
function getString(){
return string;
}
运行的程序:
<!DOCTYPE html>
<html>
<head>
<script type = "text/javascript" src="houseObject.js"></script>
<script>
var temp = new createSentence("hello world");
var string = temp.getString();
var para=document.createElement("p");
var node=document.createTextNode(string);
para.appendChild(node);
</script>
</head>
<body>
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var element=document.getElementById("div1");
element.appendChild(para);
</script>
</body>
</html>
我的第二个问题是:为什么我不能放
var element=document.getElementById("div1");
element.appendChild(para);
在 html 的头部部分。是不是因为html是脚本程序,还没有读到body部分?
提前致谢
最佳答案
您可以构建构造函数来取回对象:
var Sentence = function (text) {
this.text = text;
};
现在如果你这样做
var obj = new Sentence("Hello World");
你有一个obj instanceof Sentence
,你可以像这样访问属性
console.log(obj.text); // prints Hello World
将其“附加”到 DOM 元素是一个巨大的其他答案。参见 this question为什么直接在 DOMElement 上引用对象是危险的。也许你应该从 jQuery.data 开始或者你创建一个数组或另一个对象来存储 id/object 元组:
var list = [ obj0, obj1 ];
var keyValueStore = { "key0": obj0, "key1" : obj1 };
进一步扩展构造函数及其对象实例:
var Sentence = function (text) {
this.para = document.createElement("p");
this.setText(text);
};
Sentence.prototype.setText = function (text) {
if (this.node) {
this.para.removeChild(this.node);
}
this.node = document.createTextNode(text);
this.para.appendChild(this.node);
};
Sentence.prototype.getText = function () {
if (this.node) {
if (!this.node.textContent) {
// typical IE hack
return this.node.innerText;
}
return this.node.textContent;
}
};
用法:
window.onload = function () {
var sentence0 = new Sentence("Hello World");
document.body.appendChild(sentence0.para);
setTimeout(function () {
sentence0.setText("I'm Edward!");
}, 5000);
};
fiddle :http://jsfiddle.net/tfets/ (jsFiddle 会自动包装一个 window.load 处理程序)。
关于javascript - 基本的 Javascript 和 html 对象执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18068926/