当前位置: 动力学知识库 > 问答 > 编程问答 >

jquery - Javascript - Pull attribute into array/delete items based on attribute

问题描述:

I want to pull into an array the classes of all of the <img> in a particular <div> and then use those classes to delete the first <img> that shares that class in a different <div>.

So far, I have this that calls the original array:

var class = $('.frame div img').each(function() {

return $(this).class;

}).get();

class.forEach(function(entry) {

console.log(entry);

});

The log outputs a list of the <img></img> lines.

After that, I get stuck.

//Iterate through array and delete first <img> in #grid that has the same class, limit one per iteration.

// var img_class = $.each(class, function(key, value) {

// console.log(value);

// return $(this).attr('class');

// });

$('#grid img').each(function(){

if($(this).attr('class') == img_class){

$(this).remove();

}

});

The goals are:

  • Getting an array of classes into the img_class variable
  • Delete only the first <img> as it iterates through each class in the array

Thanks!

网友答案:

I would suggest to use some other attribute than class, eg. 'data-type'.

With the collected attribute values (e.g. 'types' array) do:

var $grid = $('#grid');

// iterate over collected types
types.forEach(function(type)) {

    // find within $grid the first <img> with data-type == type and remove it from DOM
    $grid.find('img[data-type="' + type + '"]:eq(0)').remove();
}

You could also do all in one rush:

// iterate over source <img> set
$('.frame div img').each(function() {

 // get current images type-attrib
 var type = $(this).attr('data-type');

 // find within $grid the first <img> with data-type == type and remove it from DOM
 $grid.find('img[data-type="' + type + '"]:eq(0)').remove();

});
网友答案:

I am not sure if I understood it right but would something like this be of any help?

var firstIDs = "";

$('.frame div img').each(function() {

    firstIDs += $(this).attr('id') + ",";

});

var SplitIDs = firstIDs.split(",");

$('#grid img').each(function(){

    for(var i = 0; i < SplitIDs.length; i++) {

        if($(this).attr('id') == SplitIDs[i]){

            $("#grid img #"+$(this).attr('id')+":first").remove();

        }

    }

});
网友答案:

Try

$(function() {
    var classes = $.map($(".frame div img"), function(v, k) {
      return [$(v).attr("class")];
    });
    var d = [];
    console.log($("#grid img").length);
    $.each($("#grid img"), function(k, v) {
        if ( classes.hasOwnProperty($(v).attr("class")) ) {
              d.push(v); $("body").find($(d.slice(0, 1))).remove();
            };    
    });
    console.log($("#grid img").length);
});

jsfiddle http://jsfiddle.net/guest271314/yv95C/

分享给朋友:
您可能感兴趣的文章:
随机阅读: