简体   繁体   中英

Remove image from page if it already exists

I got multiple images in different divs but sometimes 2 images are exactly the same. How do I remove all except one of those images from the page?

Is this possible with jquery/javascript? Or even css?

Example:

<div id="Content">
 <div class="Media">
  <img src="1.jpg">
 </div>
</div>
<div id="Content">
 <div class="Media">
  <img src="2.jpg">
 </div>
</div>
<div id="Content">
 <div class="Media">
  <img src="1.jpg">
 </div>
</div>
<div id="Content">
 <div class="Media">
  <img src="4.jpg">
 </div>
</div>
<div id="Content">
 <div class="Media">
  <img src="1.jpg">
 </div>
</div>

How do I make it so it only shows one of the divs with:

<img src="1.jpg">

This is the server side code It returns a big json file with all the posts from the twitter page but i didnt think it was possible to filter it so it checks for duplicates first?

       success: function(data){
           twitter = JSON.parse(data);
                for(var key in twitter.statuses){
                    if (typeof twitter.statuses[key].entities.media != "undefined") {

                            if( $.inArray(twitter.statuses[key].entities.media, container) == -1 ) {
                            container.push(twitter.statuses[key]);
                            }
                        }
                }
           },
       error: function(data){
           console.log(data);
       }

I hope someone knows how to solve this problem Thanks!

You can get all the IMG tags and see if the src is unique. If it isn't, you can remove it. Here is an example:

$(document).ready(function() {
  var img = $("img");
  var used = {};
  img.each(function() {
    var src = $(this).attr('src');
    if(used[src]) $(this).remove();
    used[src]=1;
  });
})

CodePen here: http://codepen.io/cfjedimaster/pen/tDprC

I'm using the filter function from jQuery.

First, I'm selecting all image child elements from the 'Media' class. After that, I'm using the filter function to reduce the set of matched elements to those, which aren't in my array. Then I'm deleting them. (Including the parent node)

I'm not sure whether this is the ideal solution, but you can give it a try.

$(function() {
var $allImages = $( '.Media > img' ),
    tmp,
    allUsedImageSrcs = [];

$allImages.filter( function() {
    tmp = $( this ).attr( 'src' );

    if( $.inArray( tmp, allUsedImageSrcs ) < 0 ) {
        allUsedImageSrcs.push( tmp );
        return false;
    }

    return true;
}).closest( '#Content' ).remove();});

Here's a fiddle of my implementation with jQuery, although you could achieve the same functionality without jQuery.

http://jsfiddle.net/6jb3hoc9/1/

with javascript you could do it like that (pseudo) idea

$('#content.media img'){
   //fill the array with src 
   //check if array item is same 
   //remove item 
    var array;//array of src tag
    foreach(item in array as value) 
     if(value['src'] == value['src'])
      {
           arr.remove();
          //remove item from dom **
        }

}

How to remove item from DOM http://www.w3schools.com/js/js_htmldom_nodes.asp

I have write this function for you.

 window.addEventListener("load", function () {
    var images = Array.prototype.slice.call(document.getElementsByTagName('img'));

    if (images.length == 0) {
        return;
    }

    (function handleImages(imgHash) {
        var process = function (image) {
            if (typeof imgHash[image.src] == 'undefined') {
                imgHash[image.src] = true;
            } else {
                image.parentNode.removeChild(image);
            }
        };

        setTimeout(function () {
            process(images.shift());
            if (images.length > 0) {
                setTimeout(function () {
                    handleImages(imgHash);
                }, 0);
            }
        }, 0);
    })({});
}, false);

About your other problem. You must rewrite logic into success to be asynchronous. Check this:

success: function(data){
    var twitter = JSON.parse(data);
    var props = Object.getOwnPropertyNames(twitter.statuses);
    var result = [];
    var dfd = $.Deferred();

    if (props.length == 0) {
        return;
    }

    (function handleProps(propsHash) {
        var process = function (prop) {
            if (typeof twitter.statuses[prop].entities.media != "undefined" && typeof propsHash[twitter.statuses[prop].entities.media] == 'undefined') {
                result.push(twitter.statuses[prop]);
                propsHash[twitter.statuses[prop].entities.media] = true;
            }
        };

        setTimeout(function () {
            process(props.shift());
            if (props.length > 0) {
                setTimeout(function () {
                    handleProps(propsHash);
                }, 0);
            } else {
                dfd.resolve(result);
            }
        }, 0);
    })({});

    dfd.done(function(result) {
        console.log(result);
    });
}

Instead console.log(result); you must call other code that will handle result.

Kind of don't know what you want.

Suppose you want to remove img element with the duplicated src.

// Retrieve all the images
var imgs = document.querySelectorAll(".Media > img");

// To memorize srcs appear before
var srcExisted = [];

for (var i = imgs.length - 1; i >= 0; i--) {

    if (srcExisted.indexOf(imgs[i].src) < 0) {

        // The 1st appearing, memorize
        srcExisted.push(imgs[i].src);

    } else {

        // Already existed, remove
        imgs[i].parentNode.removeChild(imgs[i]);
        imgs[i] = null;

    }
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM