【问题标题】:What's wrong with this piece of code? I don't know how to solve this issue [closed]这段代码有什么问题?我不知道如何解决这个问题[关闭]
【发布时间】:2023-03-16 03:40:01
【问题描述】:

尝试创建具有一些自定义属性的元素

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 不是函数

【问题讨论】:

  • 格式首先是错误的。
  • 不返回任何东西。您将它用作构造函数,因此它会自动将其实例化为新对象。
  • 这似乎是一个非常困惑的问题。

标签: javascript html custom-attributes


【解决方案1】:

您在函数中返回一个 HTML 元素,因此 c 将引用该元素而不是您的对象。

删除return f;,您将获得包含“hellomonkey”的警报框的预期输出

【讨论】:

  • 但是当我调用x.appendChild(document.createTextNode("I am a monkey"))时,我得到了没有appendChild()方法的错误;
  • 所以定义this.that = $(this);,然后使用x.that.appendChild();
  • @Billy Mathews,在这个问题中引入 jquery 没有用。
  • @Xotic750 你说得对,出于某种原因,我认为.appendChild 是一种jQuery 方法。所以改成this.that = this;
【解决方案2】:

你可以吗?

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");

【讨论】:

  • 我想继承该属性但我想制作一个元素
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-10
  • 2016-05-13
  • 2012-09-08
  • 2011-03-30
相关资源
最近更新 更多