好吧,这可能是一个愚蠢的问题,但我仍然在像专业人士一样学习OO javascript,所以如果这个问题有点愚蠢,请不要笑...好吧,说我有一个非常像这样的简单对象
var myObject = {
write:function(){
return 'this is a string';
}
}
现在如果在我的对象外添加以下内容(请注意我的网页中有相应的Div):
document.getElementById('myDiv').innerHTML = myObject.write();
我的div的innerHTML填充了字符串'this is a string',但是如果我只是将以下内容添加到我的脚本中(在对象之外):myObject.write()
什么都没有?有人可以告诉我为什么以及如何写入页面(不使用document.write(myObject.write())
)将字符串输出到页面。如果无法做到这一点,请告诉我原因......
抱歉,如果这是一个非常简单/愚蠢的问题,但我正在学习。
这是完整的帮助......
<html>
<head>
</head>
<body>
<div id='myDiv'></div>
<script type="text/javascript">
var myObject = {
write:function(){
return 'this is a string 2';
}
}
//document.getElementById('myDiv').innerHTML = myObject.write();
myObject.write();
</script>
</body>
</html>
答案 0 :(得分:4)
调用myObject.write()
会返回该值。由于您没有捕获并处理返回值,因此没有任何反应。
将内容写入文档的另一种方法:
<body>
<script>document.write(myObject.write())</script>
...</body> <!--document.write ONLY works as desired when the document loads.
When you call document.write() after the document has finished initiating,
nothing will happen, or the page unloads-->
答案 1 :(得分:0)
var myObject = {
obj: (function(){ return document.getElementById('myDiv');})(),
//^^set object to write to
write:function(str){
this.obj.innerHTML += str;
//^^add the string to this object
}
}
myObject.write('hello there');