document.createElement不起作用 [英] document.createElement not working
问题描述
我正在使用jQuery库创建一个插件。
I am creating a plugin using jQuery library.
这里我将 String.prototype 存储在一个变量中然后我正在使用这个变量扩展我的Sting对象。这样工作正常。
Here i am storing String.prototype in a variable then i am using this variable to extend my Sting object. And this is working fine.
// 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());
在下一种情况下,我创建m 函数xyz ,存储在$中b $ b abc 变量,这也正常。
In the next case i am creating m function xyz which stored in abc variable and this is also working fine.
function xyz(x){
alert(x)
}
var abc = xyz;
// working fine
abc("yogesh kumar");
在最后一种情况下,我将 document.createElement 存储在变量$中b $ b 标记并使用标记创建按钮。但这不起作用。
In the last case i am storing document.createElement in a variable tag and using tag to create a button. but this is not working.
var tag=document.createElement;
$(document.createElement("button")).html("document.Element").appendTo("#myDiv");
// not working
$(tag("button")).html("tag").appendTo("#myDiv");
请检查jsFiddle上的链接:
Please check the link on jsFiddle:
错误:
在Chrome中
- 未捕获TypeError:非法调用
在Firefox中
- 错误:NS_ERROR_XPC_BAD_CONVERT_JS:无法转换JavaScript
参数
为什么会出现此错误?
解决方案是什么?
推荐答案
您将获得对作为文档成员的函数的引用。当您直接调用该引用时,它的上下文现在是窗口而不是文档。以下是一个例子:
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:
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
由于上下文丢失, bar()
调用没有导致 console.log();
Since the context was lost, the bar()
call didn't result in a 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 : {}
)
}
现在你只需要 $。createElement(button)。html(tag)。appendTo(#myDiv);
它速度快且易于阅读。但请注意,IE输入有问题,如果您正在创建输入元素,我建议使用 $(< input type ='text'/>)
而不是这个。
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.
这篇关于document.createElement不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!