function mydiv(name){
this.div=document.createElement("DIV");
this.div.id=name;
this.div.innerHTML='<button id="mybtn">OK</button>';
document.body.appendChild(this.div);
document.getElementById("mybtn").onclick = this.change;
}
mydiv.prototype.change=function(){
this.div.style.background="#ff0000";
}var dd=new mydiv("abc");
this.div=document.createElement("DIV");
this.div.id=name;
this.div.innerHTML='<button id="mybtn">OK</button>';
document.body.appendChild(this.div);
document.getElementById("mybtn").onclick = this.change;
}
mydiv.prototype.change=function(){
this.div.style.background="#ff0000";
}var dd=new mydiv("abc");
我觉得问题在于,通常封装的JS对象与document.body中的显示对象是两个概念,页面上对象的事件触发似乎无法与JS封装的对象联系起来。
请不吝指导,谢谢!!!
this.div=document.createElement("DIV");
this.div.id=name;
this.div.innerHTML='<button id="mybtn">OK</button>';
document.body.appendChild(this.div);
document.getElementById("mybtn").onclick = this.change;
}
mydiv.prototype.change=function(){
this.style.background="#ff0000";
}var dd=new mydiv("abc");
你把mydiv.prototype.change方法都改了,已經改變了樓主的初衷!在給DOM對象綁定事件的時候,如果不做任何處理,被綁定方法中的this將指向到它被調用的對象,也就是被綁定的那個DOM,所以2樓的代碼將出現 'this.div is undefined' 的錯誤!需要處理一下this:<body>
<script type="text/javascript">
Function.prototype.bind = function(obj){
var foo = this;
return function(){
foo.apply(obj,arguments);
}
}
function mydiv(name){
this.div=document.createElement("DIV");
this.div.id=name;
this.div.innerHTML='<button id="mybtn">OK</button>';
document.body.appendChild(this.div);
document.getElementById("mybtn").onclick = this.change.bind(this);
}
mydiv.prototype.change=function(){
this.div.style.background="#ff0000";
}var dd=new mydiv("abc");
</script>
</body>
还有一个问题,this.change带参数怎么办?我试了下this.change.bind(this,"#00ff00")报错!
<script type="text/javascript">
Function.prototype.bind = function(obj){
var foo = this,arg = Array.prototype.slice.call(arguments,1);
return function(){
var args = Array.prototype.concat.call(arguments,arg)
foo.apply(obj,args);
}
}
function mydiv(name){
this.div=document.createElement("DIV");
this.div.id=name;
this.div.innerHTML=' <button id="mybtn">OK </button>';
document.body.appendChild(this.div);
document.getElementById("mybtn").onclick = this.change.bind(this,'#00ff00');
}
mydiv.prototype.change=function(e,rgb){
this.div.style.background = rgb||"#ff0000";
}var dd=new mydiv("abc");
</script>
</body>
<script language="javascript"> function mydiv(_id,_color){
var _div=document.createElement("DIV");
this.div = _div;
this.btn = document.createElement("input");
this.btn.type = "button";
_div.appendChild(this.btn);
_div.id = _id;
var change = function(){
_div.style.background=_color;
}
this.btn.attachEvent("onclick",change);
}
var dd = new mydiv("abc","green");
var dd2 = new mydiv("abc1","yellow");
document.body.appendChild(dd.div);
document.body.appendChild(dd2.div);</script>
</body>
</html>