HTML,Javascript中的自定义事件

var*_*nvs 7 html javascript events custom-event

我想用HTML,JS创建一个自定义事件.

<input type="text" oncustombind="foo(event);" />
Run Code Online (Sandbox Code Playgroud)

我该如何创建一个这样的?'oncustombind'是我想要创建的自定义事件.我应该能够调用oncustombind属性中定义的函数/代码.另外,我需要将一些数据传递给事件对象.

我不想使用任何库,如jquery,YUI.

任何帮助将深表感谢.

Ray*_*nos 10

你想要一个CustomEvent

它们应该易于使用,但浏览器支持很差.但是DOM-Shim应该解决这个问题.

var ev = new CustomEvent("someString");
var el = document.getElementById("someElement");
el.addEventListener("someString", function (ev) {
    // should work
});
el.dispatchEvent(ev);
Run Code Online (Sandbox Code Playgroud)


pim*_*vdb 5

使用new Functionand是不好的做法with,但这可以通过以下方式完成: http: //jsfiddle.net/pimvdb/72GwE/13/

function trigger(elem, name, e) {
    var func = new Function('e',

      'with(document) {'
    + 'with(this) {'
    + elem.getAttribute('on' + name)
    + '}'
    + '}');

    func.call(elem, e);
}
Run Code Online (Sandbox Code Playgroud)

使用以下 HTML:

<input type="text" oncustombind="console.log(e, type, getElementById);" id="x">
Run Code Online (Sandbox Code Playgroud)

然后触发事件,例如:

trigger(document.getElementById('x'), 'custombind', {foo: 123});
Run Code Online (Sandbox Code Playgroud)