Custom event in HTML, Javascript

只愿长相守 提交于 2019-11-29 10:26:23

You want a CustomEvent

They should be easy to work with but browser support is poor. However the DOM-shim should fix that.

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

It's bad practice to use new Function and with, but this can be accomplished as follows: 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);
}

With the following HTML:

<input type="text" oncustombind="console.log(e, type, getElementById);" id="x">

then trigger the event like:

trigger(document.getElementById('x'), 'custombind', {foo: 123});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!