[英]document.createElement not working
我正在使用jQuery庫創建一個插件。
在這里,我將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());
在下一種情況下,我正在創建m 函數xyz ,該函數存儲在abc變量中,並且也可以正常工作。
function xyz(x){
alert(x)
}
var abc = xyz;
// working fine
abc("yogesh kumar");
在最后一種情況下,我將document.createElement存儲在變量標簽中,並使用標簽創建按鈕。 但這不起作用。
var tag=document.createElement;
$(document.createElement("button")).html("document.Element").appendTo("#myDiv");
// not working
$(tag("button")).html("tag").appendTo("#myDiv");
請檢查jsFiddle上的鏈接:
錯誤:
在Chrome中
在Firefox中
為什么會出現這個錯誤?
解決辦法是什么?
您將獲得對作為文檔成員的函數的引用。 當您直接調用該引用時,它的上下文現在是窗口而不是文檔。 這是一個例子:
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();
顯然,這只是一個簡化的演示。
更新:對於您正在使用的用途,我建議您這樣做:
$.createElement = function(tagName,attributes){
return $(
document.createElement(tagName),
attributes ? attributes : {}
)
}
現在,您可以簡單地執行$.createElement("button").html("tag").appendTo("#myDiv");
它既快速又易於閱讀。 但是請注意,但是IE在輸入方面存在問題,如果要創建輸入元素,建議不要使用$("<input type='text' />")
。
使用bind()
方法將本機JS方法“分配”給變量:
var ce = document.createElement.bind(document);
var elem = ce('div');
alert(elem.nodeName);
在包括IE9 +的現代瀏覽器中均可使用。 對於較舊的瀏覽器,請使用包裝器功能。
這是發生因為document.createElement
使用this
內部本身。 當你稱呼它document.createElement()
則this
設置為document
。 但是,當你將它保存為一個變量,那么this
不再是document
,它的window
。
您需要使用上下文來調用它。
var tag = document.createElement; // you are saving the function, not its context
var btn = tag.call(document, 'button'); // you need to set the context
如果您的瀏覽器支持,也可以使用.bind
:
var tag = document.createElement.bind(document);
var btn = tag('button');
出現此錯誤的原因是該方法失去了上下文。 方法createElement()
必須在document
對象的上下文中調用。
在控制台中嘗試:
var tag = document.createElement;
tag.call(document, "div"); // no error
tag("div"); // error
為什么必須在document
上下文中調用createElement()
的特定細節是實現特定的,但很容易猜到。
因此,要維護上下文,請為document.createElement()
創建一個函數包裝器:
function tag(tagName) {
return document.createElement(tagName);
}
當然,jQuery還將為您創建元素:
$("<div>"); // new div element
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.