javascript
  • jquery
  • html
  • 2014-04-02 86 views 1 likes 
    1

    我試圖來處理上傳成功使用jQueryclick事件不工作jQuery的

    的單擊事件,我創建了以下使用jQuery:

    $("#uploadedImage").append("<div class='img-wrap'> 
        <span class='deletePhoto'>&times;</span> 
        <img data-id='"+files[i]+"' src='"+asset_url+"uploads/ad_photo/"+files[i]+"'> 
        </div> 
        <span class='gap'></span>"); 
    

    和處理單擊事件上面創建div的我寫這個:

    $('.img-wrap .deletePhoto').click(function() { 
        var id = $(this).closest('.img-wrap').find('img').data('id'); 
        alert(id); 
    }); 
    

    上述代碼工作正常,並創建所有的div,但是當我點擊deletePhoto範圍。沒有顯示jQuery警報。

    任何幫助或建議將是一個很大的幫助。

    在此先感謝

    回答

    3

    委託的事件和變化的建議:

    $("#uploadedImage").on('click', '.deletePhoto', function() { 
    

    你有你的活動委託給最接近的靜態父#uploadedImage你的情況這是可用頁面加載像容納新添加的div和圖像的容器。

    儘管$(document) and $(document.body)總是可用於委託事件。

    +0

    作品像魅力..非常感謝你先生.. –

    +1

    @穆罕默德很高興這有助於你,歡迎來到stackoverflow。 – Jai

    +0

    先生我正在使用'$(document).on('click','.img-wrap .deletePhoto',function(){'由你給出第一個答案..然後你已經更新了你的答案... –

    2

    在DOM加載後創建新元素時,最好使用on()。

    $(document).on('click', '.img-wrap .deletePhoto', function() { 
    
    }); 
    
    0

    試試這個:

    $(".img-wrap .deletePhoto").on('click', function() { 
    
    }); 
    
    0

    在你當你的代碼將綁定單擊事件和元素添加後必須書面另一件事綁定事件長度調試模式首先檢查。

    ,並檢查你的元素(高度和寬度),在其上點擊的CSS和是

    $(document).on('click','Your Element',function(){ 
        //your code goes in here 
    }); 
    

    威爾正常工作

    1

    你創建你的元素動態的,這就是爲什麼你需要.live() 但在新版本中不推薦使用此方法。 如果你想jQuery的使用1.10或以上,你需要打電話給你的行動以這樣的方式

    $(document).on('click','element',function(){ 
        `your code goes in here` 
    }) 
    
    0

    使用delegate

    $('#uploadedImage').on('click','.img-wrap .deletePhoto',function() { 
        var id = $(this).closest('.img-wrap').find('img').data('id'); 
        alert(id); 
    }); 
    

    詳情請參閱委託和.onhere

    0

    您可以更改在你的代碼中有一點點。

    $(".deletePhoto").off("click").on("click",function(){ 
        //Your Code here 
    }); 
    
    相關問題