Javascript -将属性拉入数组/根据属性删除项

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

本文关键字:属性 删除 Javascript 数组      更新时间:2023-09-26

我想将特定<div>中所有<img>的类拉入数组,然后使用这些类删除在不同<div>中共享该类的第一个<img>

到目前为止,我有这个调用原始数组:
var class = $('.frame div img').each(function() {
    return $(this).class;
}).get();
class.forEach(function(entry) {
    console.log(entry);
});

日志输出<img></img>行列表。

在那之后,我卡住了。

//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();
    }
});

目标是:

  • 获取类数组到img_class变量
  • 只删除第一个<img>,因为它遍历数组中的每个类

谢谢!

我不确定我是否理解正确,但这样的东西会有任何帮助吗?

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();
        }
    }
});

我建议使用class以外的其他属性,例如:"数据类型"。

使用收集的属性值(例如。

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();
}

你也可以一气呵成:

// 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();
});

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/