Custom event in HTML, Javascript

后端 未结 2 1618
自闭症患者
自闭症患者 2020-12-19 04:57

I\'m looking to create a custom event in HTML, JS.


How can I create one such? \'

相关标签:
2条回答
  • 2020-12-19 05:13

    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);
    
    0 讨论(0)
  • 2020-12-19 05:15

    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});
    
    0 讨论(0)
提交回复
热议问题