Javascript 什么';这段代码怎么了?我不知道';我不知道如何解决这个问题
尝试创建具有某些自定义属性的元素Javascript 什么';这段代码怎么了?我不知道';我不知道如何解决这个问题,javascript,html,custom-attributes,Javascript,Html,Custom Attributes,尝试创建具有某些自定义属性的元素 function x(){ var f=document.createElement("div"); this.name="monkey"; return f; } x.prototype.myFunction=function(){ alert(arguments[0]+this.name); }; var c=new x(); c.myFunction("hello"); 浏览器显示c.myFunction不是函数您在函数中
function x(){
var f=document.createElement("div");
this.name="monkey";
return f;
}
x.prototype.myFunction=function(){
alert(arguments[0]+this.name);
};
var c=new x();
c.myFunction("hello");
浏览器显示c.myFunction不是函数您在函数中返回一个HTML元素,因此
c
将引用该元素而不是对象
删除返回f代码>然后您将得到一个包含“hellomonkey”的警报框的预期输出。这对您合适吗
function x(){
var f=document.createElement("div");
this.name="monkey";
this.myFunction=function(){
alert(arguments[0]+this.name);
};
this.returnDiv = function() {
return f;
}
return this;
}
var c=new x();
c.myFunction("hello");
格式错误是第一件事。不要返回任何内容。您将其用作构造函数,因此它将自动将其实例化为新对象。这似乎是一个非常困惑的问题。我想继承该属性,但我想创建一个Elements,但当我调用x.appendChild(document.createTextNode(“我是猴子”)时,我得到一个错误,即没有appendChild()
方法
;所以定义this.that=$(this)
,然后使用x.that.appendChild()
@Billy Mathews,在这个问题中引入jquery是没有用的。@Xotic750你是对的,出于某种原因,我认为.appendChild
是一种jquery方法。所以改成this.that=this代码>