其他元素不会侦听CustomEvent

时间:2017-07-08 13:04:02

标签: javascript addeventlistener

这是我面临的简化问题。

我有一个按钮。单击此按钮时,它将调度自定义事件customClick。所以我希望其他DOM元素(如输入)来监听此自定义事件。

但输入不听。只有发送事件的按钮才会收听customClick

我做错了什么?如何让输入元素听取customClick事件?



   
var button = document.getElementById('customClick');
button.addEventListener('click', function(e){
    var clickedButton = e.currentTarget;
    var newEvent = new CustomEvent("customClick");
  
    //console.log(newEvent);
    clickedButton.dispatchEvent(newEvent);
})


button.addEventListener('customClick', function(e){

    alert('button listening customClick');
})


var input = document.getElementById('input');
    input.addEventListener('customClick', function(e){

    alert('input listening customClick');
})
   

<button id="customClick">custom click</button>
<input id="input" type="text" />
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

通过您的设置,您需要dispatchEventinput,并且:

input.dispatchEvent(newEvent);

但是,请记住,可以在按钮上的原始click事件侦听器中选择页面上的任何元素。这意味着您可以选择所有input元素,例如`document.querySelectorAll(&#39; input&#39;)。这将消除调度次要事件的需要。

&#13;
&#13;
var button = document.getElementById('customClick');
var input = document.getElementById('input');
var newEvent = new CustomEvent("customClick");

button.addEventListener('click', function(e) {
  var clickedButton = e.currentTarget;

  clickedButton.dispatchEvent(newEvent);
  input.dispatchEvent(newEvent); 
})

button.addEventListener('customClick', function(e) {
  alert('button listening customClick');
})

input.addEventListener('customClick', function(e) {
  alert('input listening customClick');
})
&#13;
<button id="customClick">custom click</button>
<input id="input" type="text" />
&#13;
&#13;
&#13;

处理此问题的更好方法可能是将customClick侦听器事件附加到window对象而不是特定input。像这样:

&#13;
&#13;
var button = document.getElementById('customClick');
var input = document.getElementById('input');
var newEvent = new CustomEvent("customButtonClick");

button.addEventListener('click', function(e) {
  var clickedButton = e.currentTarget;

  window.dispatchEvent(newEvent);

  // Any element on the page can be accessed in here. For example,
  // document.querySelectorAll('input') would select all `input`
  // elements.
})


window.addEventListener('customButtonClick', function(e) {
  alert('button listening customClick');
  
  // and access the input using `document.getElementById('input')
  // in here. However, you could just access the `input` within
  // the original button `click` event. 
})
&#13;
<button id="customClick">custom click</button>
<input id="input" type="text" />
&#13;
&#13;
&#13;