Javascript: jQuery $(this) inside map() function



我正在尝试在纯javascript map((函数中复制$(this(jQuery选择器。我想在单击一个 li 时收听并将背景图像应用于该特定的 li。

这是我的代码,但在这里,"this"不返回点击的 li 元素:

var squares = document.getElementsByClassName('box'); //returns an HTML Collection of 9 lis
           function myEvent(event) {
              squares = Array.prototype.slice.call(squares); //converts HTML collection to an Array
                squares.map(function(x, index) {
                  if (event.type === "click") {
                   this.style.backgroundImage = 'url(img/' + app.imagePath() + '.svg)';
                  }
                }, this);
              }
  squares.addEventListener("click", myEvent(), false);

有什么建议吗?

squares是一个元素列表(https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection(。您需要循环结果:

for(var i =0; i< squares.length; i++) {
  squares[i].addEventListener("click", myEvent, false);
}

此外,您传递函数引用,不要传递函数的结果(删除addEventListenermyEvent后的括号(

同样根据zer00ne awnser,所有事件功能需要做的就是:

function myEvent(event) {
    this.style.backgroundImage = 'url(img/' + app.imagePath() + '.svg)';
}

请对此进行测试:

取而代之的是:

this.style.backgroundImage....

使用这个:

event.target.style.backgroundImage

最后一个,所以把它改成event.atrget

通过在所有这些元素的父元素上注册单击事件来使用事件委派。详细信息在代码段中注释。它只涉及一个事件侦听器,它将涵盖您想要的所有可点击元素。

片段

var base = document.getElementById('base');
// When base is clicked...
base.addEventListener('click', function(event) {
  /* When an event fires it goes down from base...
  || to the very bottom element which is any of ..
  || the squares. The one that's clicked at the...
  || bottom is called event.target. It's determined...
  || by comparing the other elements in the event...
  || chain. All elements that are in the event chain...
  || are refered by the event.currentTarget property
  */
  if (event.target !== event.currentTarget) {
    var target = event.target;
    target.style.backgroundImage = 'url(http://imgh.us/Lenna.png)';
    target.style.backgroundSize = 'contain';
  }
}, false);
.box {
  width: 100px;
  height: 100px;
  border: 2px dashed red;
  cursor: pointer;
}
<section id='base'>
  <div class='box'></div>
  <div class='box'></div>
  <div class='box'></div>
  <div class='box'></div>
  <div class='box'></div>
  <div class='box'></div>
  <div class='box'></div>
  <div class='box'></div>
  <div class='box'></div>
  <div class='box'></div>
  <div class='box'></div>
  <div class='box'></div>
  <div class='box'></div>
  <div class='box'></div>
  <div class='box'></div>
</section>

最新更新