2017-02-10 21 views
-3

純粋なjavascriptのmap()関数の中に$(this)jQueryセレクタを複製しようとしています。 私はliのonclickを聞き、その特定のliに背景イメージを適用したいと思います。

は、ここに私のコードですが、ここでは、「この」クリックした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); 

任意の提案を?

+0

あなたはタイプのシナリオを "動作しない" のではなく、あなたが持っている特定のエラーを説明してもらえますか? –

+1

http://www.w3schools.com/js/js_htmldom_eventlistener.asp – Yuri

+0

クリックイベントをどのようにLiにバインドしていますか? –

答えて

1

このテストしてください:この代わりに

を:

event.target.style.backgroundImage 

と最後これがそう

+1

兄さんありがとうございますが、Andrewの答えに注意してください。それが別の問題です。 –

3

squaresをevent.atrgetすることを変更するものです。この

this.style.backgroundImage.... 

使用を要素のリスト(https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection)。すべて、zer00neのawnserあたりとしても

addEventListenermyEvent後に括弧を削除)

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

はまた、あなたが機能REFを渡し、関数の結果を渡すことはありません:あなたは結果がループする必要がありますイベント機能は次のようになります。

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

イベントの委任を使用するには、すべての要素の親にclickイベントを登録します。詳細はスニペットでコメントされています。これにはONE eventListenerが含まれ、ALLのクリック可能な要素が含まれます。

SNIPPET

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>

関連する問題