How to trigger event in JavaScript?

前端 未结 18 1854
情深已故
情深已故 2020-11-21 04:48

I have attached an event to a text box using addEventListener. It works fine. My problem arose when I wanted to trigger the event programmatically from another

18条回答
  •  死守一世寂寞
    2020-11-21 04:56

    If you are supporting IE9+ the you can use the following. The same concept is incorporated in You Might Not Need jQuery.

    function addEventListener(el, eventName, handler) {
      if (el.addEventListener) {
        el.addEventListener(eventName, handler);
      } else {
        el.attachEvent('on' + eventName, function() {
          handler.call(el);
        });
      }
    }
    
    function triggerEvent(el, eventName, options) {
      var event;
      if (window.CustomEvent) {
        event = new CustomEvent(eventName, options);
      } else {
        event = document.createEvent('CustomEvent');
        event.initCustomEvent(eventName, true, true, options);
      }
      el.dispatchEvent(event);
    }
    
    // Add an event listener.
    addEventListener(document, 'customChangeEvent', function(e) {
      document.body.innerHTML = e.detail;
    });
    
    // Trigger the event.
    triggerEvent(document, 'customChangeEvent', {
      detail: 'Display on trigger...'
    });


    If you are already using jQuery, here is the jQuery version of the code above.

    $(function() {
      // Add an event listener.
      $(document).on('customChangeEvent', function(e, opts) {
        $('body').html(opts.detail);
      });
    
      // Trigger the event.
      $(document).trigger('customChangeEvent', {
        detail: 'Display on trigger...'
      });
    });

提交回复
热议问题