2015-11-19 60 views
0

這是我第一篇文章。我是jQuery中的新成員,我正在嘗試創建一個Web Gallery。問題在於我在滑塊下有一些子彈圖像,它們顯示當前顯示的圖像。 這是產生子彈jQuery代碼:jQuery事件沒有被第二次觸發,因爲另一個函數

function updateProgress() { 
    var txt = ""; 
    for(i=1;i<$slides.length;i++) // Here $slides is a jQuery object; 
    { 
     if(i != currentSlide) 
      txt += '<img src="Images/empty_dot.png" class="dot" data-dot-id="'+i+'" />'; 
     else 
      txt += '<img src="Images/full_dot.png" data-dot-id="'+i+'" />'; 
    } 
    $("#progress").html(txt); 
} 

如果我檢查的元素,它看起來像這樣:

<div id="progress"> 
    <img src="Images/full_dot.png" class="dot" data-dot-id="1" /> 
    <img src="Images/empty_dot.png" class="dot" data-dot-id="2" /> 
    <img src="Images/empty_dot.png" class="dot" data-dot-id="3" /> 
    <img src="Images/empty_dot.png" class="dot" data-dot-id="4" /> 
</div> 

然後,不會觸發回調是這樣的:

$(".dot").on("click",gotoImage); 

而且gotoImage功能:

function gotoImage() { 
    var imgId = $(this).attr("data-dot-id"); 
    var go_to = 1000*(imgId-1)*-1; 
    if(imgId == 1) go_to = 0; 
    $slider.css('margin-left',go_to); 
    currentSlide = imgId; 
    updateProgress(); 
    //alert(currentSlide); 
} 

我測試了這個函數,看看哪一行阻止了它被調用,並且我發現它是因爲updateProgress(),如前所示。此外,我添加了alert()以查看該函數何時被調用。

當我的頁面被加載時,我調用updateProgress()一次來顯示項目符號。然後,如果我再次調用它,在任何情況下,.on('click',function(){})事件將不再起作用。因此,爲了更簡單:我加載頁面,加載後調用updateProgress(),然後點擊其中一個點(以便再次調用updateProgress())。發生這種情況後,點擊事件將不起作用。

你能解釋一下爲什麼嗎?我只是想不通......

這裏是整個頁面的小提琴:https://jsfiddle.net/antonioo/49gzp3n0/1/

謝謝!

回答

0

你可能想attach the event on the parent element

$("#progress").on("click", ".dot", gotoImage); 

這種方式,點擊後.on冒泡DOM樹添加到#progress元素的元素,並導致gotoImage被調用。


概念,而不是重新建立每次HTML目前的有源元件的變化,你可以改變src圖像的屬性:

function updateProgress() { 
    $('.dot').each(function (index, image) { 
    var dotImage = (index == currentSlide) ? 'full_dot.png' : 'empty_dot.png'; 
    $(image).attr('src', 'Images/' + dotImage); 
    }); 
} 

或者只是改變了圓點src屬性這是之前選擇和所述一個現在選擇圖像:

function gotoImage() { 
    var imgId = $(this).attr("data-dot-id"); 
    var go_to = 1000*(imgId-1)*-1; 
    if (imgId == 1) go_to = 0; 
    $slider.css('margin-left', go_to); 
    // lines below changed 
    $('.dot').eq(currentSlide || 0).attr('src', 'Images/empty_dot.png'); 
    currentSlide = imgId; 
    $(this).attr('src', 'Images/full_dot.png'); 
} 
+0

非常感謝,它工作得很好!我也會考慮你的選擇。 – Antonio

相關問題