2012-11-12 53 views
2

在Widget Factory中對jQuery對象使用$ .extend時,IE8似乎在新創建的對象上丟失了jQuery上下文。讓我來證明一下。

下面的代碼工作在IE9 +,Chrome瀏覽器,火狐

$.widget("a07.Wooh", { 
    options: { 
     test: "Awesome" 
    }, 
    _testFunc: function() { 
     // Perform some operations on the DOM using this.element jQuery Object 
     this.element.after("<div class=\"stuff\">Some cool stuff</div>").next().hide(); 
    }, 
    _testFunc2: function() { 
     //Copy the this.element object 
     this.element2 = $.extend({}, this.element); 

     //Perform some operations on the DOM using this.element2 jQuery Object 
     this.element2.next().css('color', 'red').show(); 
    }, 
    _create: function() { 
     this._testFunc(); 
     this._testFunc2(); 
    }, 
    _init: function() {} 
}); 

The working jsfiddle

正如上面所提到的,此代碼工作正常,在所有主要的瀏覽器除了 IE8。基本上它返回和用於this.element2.next().css().show()線錯誤消息:

對象不支持此屬性或方法

屬性/方法其參考是jQuery方法下(),CSS()並顯示()

它看起來好像在IE8中this.element2已經失去了它的jQuery上下文,因爲如果我把對象包裝在一個像這樣的jQuery函數:this.element2 = $(this.element2);一切都很好。

The IE8 compatible jsfiddle

所以現在的問題是,這是怎麼回事嗎?這是IE8的標準行爲還是我不正確地接近編程的情況?

+1

'this.element2 = $ .extend({},this.element);' - 你在這裏有什麼打算? –

+0

你的小提琴在我的IE8中工作。 –

+0

如果它在你的IE8中有效,你可能會安裝Chrome Frame或處於某種第三維兼容模式?它在我的本地測試IE8和BrowserStack上的確切行上出現相同的錯誤時失敗。 – EasyCo

回答

1

如果您的意圖是僅創建包含相同元素的單獨jQuery對象,那麼這個怎麼樣:

this.element2 = $(this.element[0]); 
+0

或'this.element2 = this.element.clone()' – charlietfl

+0

@charlietfl不會工作,因爲它會創建元素的副本,但對特定DOM元素的引用會丟失。 – EasyCo

+0

@EasyCo OK ..我仔細看了看小提琴。如果你想在DOM中引用元素,首先要做的就是創建副本 – charlietfl