prototype.js 1.6.0 の DOM Builder で hello world
new Element('button',{onclick:"alert('hello world')"})
とやれば、
<button onclick="alert('hello world')"></button>
になる。と思ったらダメだった。
Firefoxは大丈夫ですが、IEで動きません。
内部でsetAttributeが使われていて、setAttribute(onclick,"alert('hello world')")となるからです。
IEではsetAttributeの第2引数には関数オブジェクトを渡す必要があります
こう書けばIEで動きます。でも、Firefoxでは動きません。
new Element('button',{onclick:new Function("alert('hello world')")});
結局、こう書くことになります。
var elt = new Element('button'); elt.observe('click',function () {alert('hello world')}); あるいは elt.onclick = function() {alert('hello world')};
おさらい
- prototype.js 1.6.0 の DOM Builder は 内部で setAttribute を使っているので、そこにはイベントハンドラを書くべきでない。
- イベントハンドラはEvent.observeを使おう。
Builder.node('button',{onclick:"alert('hello world')"})
は、IEでもFirefoxでも動きます。内部でsetAttributeを使っていないので。
script.aculo.usと同じかと思っていたら痛い目をみました。