簡體   English   中英

如果img src損壞,則刪除父元素和所有子元素

[英]Delete parent element and all children if img src broken

我正在做一個Ajax查詢,它向后拉一個JSON數組,其中填充了約50個指向圖像的URL。 然后,我在數組上使用forEach生成與其他<div>嵌套的<div> ,其中一個<div>持有一個<img>元素,在其中我將src設置為與forEach迭代中的當前url相等。

問題是某些URL已死,並導致<img>元素損壞(您知道,是否有翻錄文件的小圖像?)。 所以我要做的是,在迭代過程中,當我創建我的<img>元素時,我將onerror屬性設置為等於"$(this).closest('.gramDiv').remove()" ,該嘗試刪除一個某些<img>父元素以及該父元素的所有子元素。 這行得通,但是我覺得這有點拙劣,不是最佳實踐。 是否有更標准化的方法?

$(document).ready(function(){
    console.log("Ready");


        function adder(data,status){

            data.forEach((url,index)=>{
                let attrObj = {
                    src: url,
                    alt: 'photo ' + index, 
                    onerror: "$(this).closest('.targetDiv').remove()"
                };

                let img = $('<img>').attr(attrObj);

                let targetDiv = $('<div></div>').addClass('target');
                let picDiv = $('<div></div>').addClass('picDiv').append(img);

                let component = targetDiv.append(picDiv);

                $('#bodyDiv').append(component);
            })
        }  

        $.ajax({
            url:'https:/blahblahblah.json',
            dataType: 'json',
            success: adder,
            timeout: 3000,
            error: function(){ alert('error retrieving')}
        });


})

您可以嘗試使用此代碼

$("<img/>")
    .on('load', function() { console.log("image loaded correctly"); })
    .on('error', function() { console.log("error loading image"); })
    .attr("src", $(originalImage).attr("src"))
;

這里

感謝@SabirAmeen和此鏈接的答案。

基本上,在forEach塊中,您想在當前迭代的URL上運行另一個ajax調用,並檢索其status ,以指示其是否正常工作。 在我的情況下,工作status200 ,而我認為其他任何情況都已損壞。

我從上面簡化了我的代碼,但仍然說明了這一點:

$(document).ready(function(){
    console.log("Ready");


        //event.preventDefault();
        console.log("pressed");

        function adder(data,status){

            data = data.reduce(function(a,b){
                if(!a.includes(b)) a.push(b);
                return a;
            },[]);

            data.forEach((url,index)=>{             

                UrlExists(url, function(status){
                    if(status === 200){
                       // file was found
                       console.log('found:',status);
                       let img = $('<img>').attr('src',url);
                       $('body').append(img);
                    }
                    else {
                       // do nothing
                       console.log('not found:',status);
                    }
                });
            })
        }

        function UrlExists(url, cb){
            jQuery.ajax({
                url:      url,
                dataType: 'text',
                type:     'GET',
                complete:  function(xhr){
                    if(typeof cb === 'function')
                       cb.apply(this, [xhr.status]);
                }
            });
        }

        $.ajax({
            url:'https://yaddayadda.json',
            dataType: 'json',
            // success: adder,
            success: adder,
            //complete: remover,
            timeout: 3000,
            error: function(){ alert('error retrieving data fam')}
        });

})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM