2016-11-07 65 views
0

HTML代碼:jQuery開發的簡單功能無法正常工作

$('.alertme').click(function(){ 
 
     alert('By selecting new image your old image will be remove'); 
 
     $(this).removeClass('alertme'); 
 
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
#Before a Function is executed 
 
    <input type="file" name="efile" id="efile" style="width:100%" class="alertme"> 
 
    #After a function is executed 
 
    <input type="file" name="efile" id="efile" style="width:100%" class="">

它仍然是一個執行的函數後提醒我。我不知道它爲什麼會發生?你能幫我麼?你的幫助表示讚賞。

+0

沒有重複的ID! – Li357

+0

@Andrew Li我的功能是基於班級。 –

回答

1

刪除類不會刪除附加的事件處理程序。使用off()方法刪除事件處理程序。

$('.alertme').click(function(){ 
    alert('By selecting new image your old image will be remove'); 
    $(this).off('click').removeClass('alertme'); 
}); 
+0

感謝您提供的答案 –

+0

@RushabhShah:很高興幫助 –

0

再次遍歷檢查dom元素或類是否被刪除使用通過事件委託。

$(document).on('click', '.alertme', function(){ 
    alert('By selecting new image your old image will be remove'); 
    $(this).removeClass('alertme'); 
}); 
0

您應該使用.one()

附加的處理程序爲元素的事件。處理程序每​​個事件類型每個元素最多執行一次。

$('.alertme').one('click', function(){ 
    alert('By selecting new image your old image will be remove'); 
    $(this).removeClass('alertme'); 
}); 

但更好的選擇是使用.on()委派事件的方法,當操作選擇器(如刪除或添加類)使用Event Delegation

$(document).on('click', '.alertme', function(){ 
    alert('By selecting new image your old image will be remove'); 
    $(this).removeClass('alertme'); 
});