你如何扩展dom中的堆栈元素?

时间:2011-04-19 09:36:49

标签: javascript dom html5

我成功地延长了Element,例如,

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是有意义的,因为只有Select可以有Option个孩子。 Select的{​​{1}}方法也相当蹩脚。

2 个答案:

答案 0 :(得分:3)

不确定您从哪里获得Element.Select,但它不是本机对象。您需要HTMLSelectElement代替MDC reference)。


注意:请阅读评论中指出的this article,了解扩展DOM的原因。

答案 1 :(得分: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