2011-04-19 75 views
0

很成功地延伸Element S,例如,如何擴展dom中的堆棧元素?

Element.prototype.ancestorByTagName = function(tagName) { ... } 

但不能弄清楚如何具體地延長Select元件

例如,每個以下的失敗:

Select.prototype.appendOption = function(value, label, select_value) { ... } 
Element.Select.prototype.appendOption = function(value, label, select_value) { ... } 

上午在虧損。

在這種情況下

是有道理的新方法appendOption它限制在Select對所有Element S,因爲只有Select可以有Option孩子。 Selectadd方法也很蹩腳。

+1

您定位了哪個瀏覽器?期望所有瀏覽器都實現相同的繼承模型或任何繼承模型,這有點雄心勃勃。你有沒有讀過Kangax's *擴展DOM *有什麼問題?(http://perfectionkills.com/whats-wrong-with-extending-the-dom/)? – RobG 2011-04-19 09:47:41

+0

有趣。 http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-94282980 – mplungjan 2011-04-19 09:51:29

+0

@RobG - 在Chrome之後,也許在Firefox稍後。絕對同意延長dom的危險 - 大部分時間使用命名構造來隔離工作。在這種情況下,我的一個智力練習,填補我認爲是非常基本的dom功能 – 2011-04-19 09:56:29

回答

3

不知道從何處取得Element.Select但它不是一個本地對象。你想要HTMLSelectElement而不是(MDC reference)。


注意:閱盡this article,在評論中指出,爲什麼不延長DOM。

+0

你是對的,我覺得這很愚蠢。從示例中使用「元素」而不是「HTMLElement」,並讓自己感到困惑。 – 2011-04-19 10:05:05

+0

閱讀關於擴展DOM的文章。最後它說,在一個單一的環境中,它可能沒問題 - 鉻和後來的Firefox。如果有人付給我很多錢,我會付給某人編寫一個翻譯成IE的。 – 2011-04-19 10:25:03

0

下面是一些在Firefox 4

<script> 
if (HTMLSelectElement) HTMLSelectElement.prototype.addOption = function(text,value) { 
    this.options[this.options.length]= new Option(value,text) 
} 
else alert("It's not called HTMLSelectElement") 
window.onload=function() { 
    document.getElementById('sel1').addOption("Hi","There") 
} 
</script> 
<select id="sel1"></select> 

工作,給了我這個在IE8

網頁錯誤的詳細信息

Message: 'HTMLSelectElement' is undefined 
Line: 2 
Char: 1 
Code: 0 
URI: file:///C:/TEMP/addoption.html