今天把自己给坑了,在大型项目中,你能看出来坑在哪里吗?
发布于 11 年前 作者 think2011 4314 次浏览 最后一次编辑是 9 年前 来自 分享

以下情况,#demo1 永远不会变色,知道为什么吗?

这个把我坑惨了,在复杂的构造函数中很难找出原因,也说明了基础很重要,哦不,实战更重要。

javascript版

var Test1, demo1;
Test1 = (function() {
 function Test1(el) {
 this.el = el;
 this.set1();
 this.set2();
 }
 Test1.prototype.set1 = function() {
 var p;
 p = "<p>这是一个测试</p>";
 return document.body.innerHTML += p;
 };
 Test1.prototype.set2 = function() {
 return this.el.style.background = 'blue';
 };
 return Test1;
})();
demo1 = new Test1(document.querySelector('#demo1'));

coffee版

class Test1
 constructor: (el) ->
 @el = el
 @set1()
 @set2()
 
 set1: ->
 p = """<p>这是一个测试</p>"""
 document.body.innerHTML += p
 
 set2: ->
 @el.style.background = 'blue'
 
demo1 = new Test1 document.querySelector('#demo1')
8 回复

看不懂。。

是不是你在用innerHTML的时候刷新了dom树,重新生成了 #demo1啊。。。 看到你贴了这两个版本,还以为是构造函数的坑呢

@waksana +1

var Test1, demo1;
Test1 = (function() {
 function Test1(el) {
 this.el = el;
 this.set1();
 console.log(this.el===document.querySelector('#demo1')) //false
 this.set2();
 }
 Test1.prototype.set1 = function() {
 var p;
 p = "<p>这是一个测试</p>";
 return document.body.innerHTML += p;
 };
 Test1.prototype.set2 = function() {
 return this.el.style.background = 'blue';
 };
 return Test1;
})();
demo1 = new Test1(document.querySelector('#demo1'));

看到document.body.innerHTML感觉挺突兀的,改成this.el.innerHTML就好了。

@pockry @waksana 是的,重点在于dom树被刷新了,所以之前取得的元素都失效了。

第一个set1把body内容都换掉了

document.body.innerHTML += p;

回到顶部

AltStyle によって変換されたページ (->オリジナル) /