2016-03-01 175 views
0

我有一個上市的HTML結構如下函數調用多次

<li class="game-box showlist" id="papp_1249" data-tag="Junior KG,Maths"> 
    <div class="game-box-link" 
     data-id="1249" data-active="yes" data-orientation="landscape" 
     data-ajax="false" data-url="http://totsmart.in/scale_concept" 
     data-transition="none"> 

    <img src="http://example.com/abc.jpg" class="game-thumb"> 
    </div> 
    <div class="game-title"> 
    <div class="btn-container"> 
     <a href="#login" class="box-btn4"> 
     <img src="css/assets/Login.png"> 
     </a> 
     <div class="box-btn4 price-btn"> 
     //clicking this using trigger 
     <span class="game-price buy" data-id="">Free</span> 
     </div> 
     <span class="sm_box-btn expand"> 
      <img src="css/assets/drop.png"> 
     </span> 
     <div data-id="1249" data-active="yes" data-orientation="landscape" 
      data-ajax="false" data-url="http://example.in/scale_concept" 
      data-transition="none" class="game-box-play-link sm_box-btn"> 

     <img src="css/assets/Play.png"> 
     </div> 
    </div> 
    <div class="game-content"> 
     <p><strong>Subject</strong>: Maths 
     <br> 
     <strong>Class</strong>: KG – KG – Junior &amp; Senior 
     <br> 
     <strong>Description</strong> 
     <br>Drag and drop objects to one out of the two empty boxes and practice the scale concepts like – Big-Small, Fast-Slow, Tall-Short etc. 
     </p> 
    </div> 
    </div><span class="game-box-title">Scale concepts</span> 
</li> 

我的JavaScript功能

$("body").on('vclick', '.game-box-link, .game-box-play-link', function (e) { 
    e.preventDefault(); 
    var application_id = $(this).data('id'); 
    console.log('game-play-clicked'); 
    check_app(application_id, this); 
}); 

check_app(application_id, item) 
{ 
     alert('clicked'); 
     var game_id = $(item).data('id'); 
     if ("ios" != deviceType()) { 
      $('#papp_'+game_id+' .buy').trigger("vclick"); 
      console.log('triggered'); 
     } 
} 

我的問題是,當我點擊game-box-link DIV首次然後check_app()呼籲一個時間,如果我第二次點擊它check_app()要求2次,依此類推。我需要它只被調用一次。我做錯了,請幫助我。您的幫助將不勝感激。

這是我的控制檯日誌的屏幕截圖。你可以看到它火了7倍

enter image description here

+0

不,我沒有循環它。 – Vinie

+1

'this'不能被接受爲'argument' .. – Rayon

+0

你的函數應該看起來像'function check_app(application_id,_this){alert('clicked');}'以'function'開始。 –

回答

0

添加e.stopPropagation();給你的函數。

$("body").on('vclick', '.game-box-link, .game-box-play-link', function (e) { 
    e.preventDefault(); 
    e.stopPropagation(); 
    var application_id = $(this).data('id'); 
    console.log('game-play-clicked'); 
    check_app(application_id, this); 
}); 

check_app(application_id, this) 
{ 
     alert('clicked'); 
} 

孩子上的click事件也發生在父母身上,這就是爲什麼事件被觸發多次。

+0

父元素是'li',你確定它發生了嗎? – Jai

+0

@Vinie奇怪的行爲不是嗎??????? – Jai

+0

仍然多次發射 – Vinie