javascript document.createElement 不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14202699/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 20:59:51  来源:igfitidea点击:

document.createElement not working

javascriptjquery

提问by yoku2010

I am creating a plugin using jQuery library.

我正在使用 jQuery 库创建一个插件。

Here i am storing String.prototypein a variable then i am using this variable to extend my Sting object. And this is working fine.

在这里,我将String.prototype存储在一个变量中,然后我使用这个变量来扩展我的 Sting 对象。这工作正常。

// String Prototyping store in a variable
// Save bytes in the minified version of js
var StrProto = String.prototype;
String.prototype.toProperCase = function () {
  return this.replace(/\w\S*/g, function (txt) {
    return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
  });
};
// working fine
alert("yogesh kumar".toProperCase());

In the next case i am creating m function xyzwhich stored in abcvariable and this is also working fine.

在下一种情况下,我正在创建存储在abc变量中的m函数 xyz, 这也工作正常。

function xyz(x){
  alert(x)
}
var abc = xyz;
// working fine
abc("yogesh kumar");

In the last case i am storing document.createElementin a variable tagand using tag to create a button. but this is not working.

在最后一种情况下,我将document.createElement存储在变量 标签中并使用标签创建一个按钮。但这不起作用。

var tag=document.createElement;
$(document.createElement("button")).html("document.Element").appendTo("#myDiv");

// not working
$(tag("button")).html("tag").appendTo("#myDiv");

Please check the link on jsFiddle:

请检查jsFiddle上的链接:

click here

点击这里

Error:

错误:

In Chrome

在 Chrome 中

  • Uncaught TypeError: Illegal invocation
  • 未捕获的类型错误:非法调用

in Firefox

在 Firefox 中

  • Error: NS_ERROR_XPC_BAD_CONVERT_JS: Could not convert JavaScript argument
  • 错误:NS_ERROR_XPC_BAD_CONVERT_JS:无法转换 JavaScript 参数

Why this error?

为什么会出现这个错误?

What is the solution?

解决办法是什么?

回答by Kevin B

You are getting a reference to a function that is a member of the document. When you call that reference directly, it's context is now the window rather than the document. Here's an example:

您正在获取对作为文档成员的函数的引用。当您直接调用该引用时,它的上下文现在是窗口而不是文档。下面是一个例子:

http://jsfiddle.net/DeCNx/

http://jsfiddle.net/DeCNx/

var foo = {
  createElement: function(tagname) {
    if (this._secretvarthatisneeded) {
      console.log(tagname + " Element Created!");
    }
  },
  _secretvarthatisneeded: true
}

foo.createElement("FOOBAR"); // works

var bar = foo.createElement;
bar("BARFOO"); // doesn't work
bar.call(foo,"BARBAR") // works

Since the context was lost, the bar()call didn't result in a console.log();

由于上下文丢失,bar()调用不会导致console.log();

obviously this is just a simplification to demonstrate.

显然,这只是为了演示的简化。

Update: For the use you are making, i'd suggest doing this:

更新:对于您正在使用的用途,我建议您这样做:

$.createElement = function(tagName,attributes){
    return $(
        document.createElement(tagName),
        attributes ? attributes : {}
    )
}

Now you can simply do $.createElement("button").html("tag").appendTo("#myDiv");It is fast and still easy to read. Note however IE has problems with inputs, if you're creating input elements, i suggest using $("<input type='text' />")rather than this.

现在你可以简单地做$.createElement("button").html("tag").appendTo("#myDiv");它很快而且仍然很容易阅读。但是请注意 IE 有输入问题,如果您正在创建输入元素,我建议使用$("<input type='text' />")而不是这个。

回答by Marat Tanalin

Use the bind()method for "assigning" the native JS method to a variable:

使用bind()将原生 JS 方法“分配”给变量的方法:

var ce = document.createElement.bind(document);
var elem = ce('div');
alert(elem.nodeName);

Works in modern browsers including IE9+. For older browsers, use a wrapper function.

适用于现代浏览器,包括 IE9+。对于较旧的浏览器,请使用包装函数。

回答by VisioN

jQuery can create new elementsfor you as simple as:

jQuery 可以为您创建新元素,就像:

$("<button />").html("document.Element").appendTo("#myDiv");

To have a reason why your approach is not working, read @Kevin's commentbelow.

要了解您的方法不起作用的原因,请阅读下面@Kevin 的评论

回答by Rocket Hazmat

That is happening because document.createElementuses thisinside itself. When you call it like document.createElement()then thisis set to document. But, when you save it as a variable, then thisis no longer document, it's window.

发生这种情况是因为在其内部document.createElement使用this。当你调用它时document.createElement()thenthis设置为document. 但是,当您将其另存为变量时,则this不再是document,而是window

You need to call it with the context.

您需要使用上下文来调用它。

var tag = document.createElement;  // you are saving the function, not its context
var btn = tag.call(document, 'button'); // you need to set the context

If your browser supports it, you can also use .bind:

如果您的浏览器支持,您还可以使用.bind

var tag = document.createElement.bind(document);
var btn = tag('button');

回答by gilly3

The reason for this error is that the method lost its context. The method createElement()must be called in the context of a documentobject.

此错误的原因是该方法丢失了其上下文。该方法createElement()必须在document对象的上下文中调用。

Try this in a console:

在控制台中试试这个:

var tag = document.createElement;
tag.call(document, "div");  // no error
tag("div");  // error

The specific details of why createElement()must be called in the context of documentare implementation specific, but can easily be guessed at.

为什么createElement()必须在上下文中调用的具体细节是特定于document实现的,但很容易被猜到。

So, to maintain context, create a function wrapper for document.createElement():

因此,要维护上下文,请为以下对象创建一个函数包装器document.createElement()

function tag(tagName) {
    return document.createElement(tagName);
}

Of course, jQuery will also create elements for you:

当然,jQuery 也会为你创建元素:

$("<div>");  // new div element