简体   繁体   English

在“addEventListener”中使用具有两个函数的 function 不起作用

[英]Using a function with two functions within in 'addEventListener' is not working

I've added two event listeners to a range element and I want to update its value while it's modified... It doesn't update if I add two functions within one in the addEventListener method, but I can do it if they are separated.我已经向范围元素添加了两个事件侦听器,并且我想在修改它时更新它的值......如果我在 addEventListener 方法中添加两个函数,它不会更新,但如果它们是分开的,我可以做到.

 const input = document.getElementById('blur'); const span = document.getElementById('blur-value'); function updateBlur() { const suffix = input.dataset.sizing || ''; document.documentElement.style.setProperty(`--${this.name}`, this.value + suffix); } function updateSpan() { span.innerText = input.value; } //This does not work input.addEventListener('mousemove', ()=>{ updateBlur(); updateSpan(); }); //This is the workaround /* input.addEventListener('mousemove',updateBlur); input.addEventListener('mousemove',updateSpan); */
 :root { --blur: 10px; } img { filter: blur(var(--blur)); }
 <div> <label for="blur">Blur:</label> <input id="blur" type="range" name="blur" min="0" max="25" value="10" data-sizing="px"> <span id="blur-value">Value</span> </div> <img src="https://source.unsplash.com/7bwQXzbF6KE/" width=400px heigh=400px>

The problem was with the this reference, when you are calling from a event callback function, it loosing the this reference.问题在于this引用,当您从事件回调 function 调用时,它失去了this引用。 Here is an updated function used, that can solve this issue.这是一个更新的 function 使用,可以解决这个问题。

function updateBlur() {
  const suffix = input.dataset.sizing || '';
  // this reference getting lost when you are calling from a callback function instead of binding in the event.
   
  document.documentElement.style.setProperty(`--${input.name}`, input.value + suffix);
}

 const input = document.getElementById('blur'); const span = document.getElementById('blur-value'); function updateBlur() { const suffix = input.dataset.sizing || ''; // this reference getting lost when you are calling from a callback function instead of binding in the event. document.documentElement.style.setProperty(`--${input.name}`, input.value + suffix); } function updateSpan() { span.innerText = input.value; } //This does not work input.addEventListener('mousemove', ()=>{ updateBlur(); updateSpan(); }); //This is the workaround /* input.addEventListener('mousemove',updateBlur); input.addEventListener('mousemove',updateSpan); */
 :root { --blur: 10px; } img { filter: blur(var(--blur)); }
 <div> <label for="blur">Blur:</label> <input id="blur" type="range" name="blur" min="0" max="25" value="10" data-sizing="px"> <span id="blur-value">Value</span> </div> <img src="https://source.unsplash.com/7bwQXzbF6KE/" width=400px heigh=400px>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM