突出显示重复的行值的JavaScript

问题描述 投票:2回答:6

我使用JS突出表中的重复值。

什么基本的代码是做在一个阵列中添加表行的值,然后,如果它存在,比较,然后突出显示该行。

该代码工作正常,但它凸显了相同的颜色(红色)的所有重复值。我需要做的是要突出每组相似值的不同的颜色。可以说我有4组重复的值,每个组应以不同的颜色来突出显示。也许颜色需随机产生如表中可能有多个重复的值。

 $(function() {
    var tableRows = $("#sortable tbody tr"); //find all the rows
    var rowValues = []; //to keep track of which values appear more than once
    tableRows.each(function() { 
        var rowValue = $(this).find(".content").html();
        if (!rowValues[rowValue]) {
            var rowComposite = new Object();
            rowComposite.count = 1;
            rowComposite.row = this;
            rowValues[rowValue] = rowComposite;
        } else {
            var rowComposite = rowValues[rowValue];
            if (rowComposite.count == 1) {
                $(rowComposite.row).css('backgroundColor', 'red');
            }
            $(this).css('backgroundColor', 'red');
            rowComposite.count++;
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="sortable">
    <tbody>
        <tr>
            <td class="content">A</td>
        </tr>
        <tr>
            <td class="content">B</td>
        </tr>
        <tr>
            <td class="content">A</td>
        </tr>
         <tr>
            <td class="content">C</td>
        </tr>
         <tr>
            <td class="content">C</td>
        </tr>
    </tbody>
</table>
javascript jquery arrays string dom
6个回答
2
投票

代替为arrayrowValues的,你最好使用object,所以你可以检查在key价值的存在。

您还可以使用的从你在哪里得到动态的颜色,并保持移位array,无论何时你发现一个新的价值色彩的array,所以每个不同的值将有其相关的不同颜色。

而且也没有必要检查在countelse,因为每当你达到这个块就意味着这个value已经存在于array

这是应该的代码:

$(function() {
  var tableRows = $("#sortable tbody tr"); //find all the rows
  var colors = ["red", "blue", "green", "yellow", "#f5b"];
  var rowValues = {};
  tableRows.each(function() {
    var rowValue = $(this).find(".content").html();
    if (!rowValues[rowValue]) {
      var rowComposite = new Object();
      rowComposite.count = 1;
      rowComposite.row = this;
      rowValues[rowValue] = rowComposite;
    } else {
      var rowComposite = rowValues[rowValue];
      if (!rowComposite.color) {
        rowComposite.color = colors.shift();
      }
      rowComposite.count++;
      $(this).css('backgroundColor', rowComposite.color);
      $(rowComposite.row).css('backgroundColor', rowComposite.color);
    }
  });
});

演示:

$(function() {
  var tableRows = $("#sortable tbody tr"); //find all the rows
  var colors = ["red", "blue", "green", "yellow", "#f5b"];
  var rowValues = {};
  tableRows.each(function() {
    var rowValue = $(this).find(".content").html();
    if (!rowValues[rowValue]) {
      var rowComposite = new Object();
      rowComposite.count = 1;
      rowComposite.row = this;
      rowComposite.color = colors.shift();
      rowValues[rowValue] = rowComposite;
    } else {
      var rowComposite = rowValues[rowValue];
      rowComposite.count++;
      $(this).css('backgroundColor', rowComposite.color);
      $(rowComposite.row).css('backgroundColor', rowComposite.color);
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="sortable">
  <tbody>
    <tr>
      <td class="content">A</td>
    </tr>
    <tr>
      <td class="content">B</td>
    </tr>
    <tr>
      <td class="content">A</td>
    </tr>
    <tr>
      <td class="content">C</td>
    </tr>
    <tr>
      <td class="content">C</td>
    </tr>
  </tbody>
</table>

1
投票

我想创建每个内容文本的阵列具有相同内容的单元格。一旦你有了这个,你可以遍历它,并根据需要选中的单元格。

要生成随机颜色我已经添加了有一组跟踪所产生的颜色的方法。它会检查是否有随机生成的颜色以前已经取得并保持,直到产生一个独特的颜色产生颜色。

这是可能的,你风与色彩,使文字难以辨认或两个随机颜色没有足够的对比度,告诉他们分开。因此,这不是一个完美的解决方案。

function generateRandomInt(max, min = 0) {
  return Math.floor(Math.random() * (max - min + 1) + min);
}

/**
 * This method will return a new method, when the returned method is 
 * called it will return a unique color. Subsequent calls to the color
 * generator will never return the same color.
 */
function colorGenerator() {
  // Create a Set at the function scope which we can use to keep
  // track of the colors generated by the returned method.
  const
    generatedColors = new Set();
    
  return () => {
    let randomColor;
    // Keep generating a random color in the format "rgb(R,G,B)" until 
    // a color is generated that doesn't yet exist in the set. This doesn't
    // take into account that at some point you'll run out of 
    // possible colors (but it will take 16M+ tries).
    do {
      randomColor = `rgb(${generateRandomInt(255)},${generateRandomInt(255)},${generateRandomInt(255)})`;
    } while (generatedColors.has(randomColor));
    
    // Add the generated, unique, color to the set.
    generatedColors.add(randomColor);
    
    // Return the random color.
    return randomColor;  
  };
}

function highlightDoubles(table) {
  const
    // Get all the element with the content CSS class.
    contentCells = table.querySelectorAll('.content'),
    // Create map, the cell content will be the key and the value will be
    // an array with cells that have the key as content.
    contentMap = new Map();
   
  // IE doesn't support forEach on a NodeList, convert it to an array first.
  Array.from(contentCells).forEach(cell => {
    const
      // For each cell check if the content has been encountered before. If so
      // return the map value and else create a new array.
      array = (contentMap.has(cell.textContent))
        ? contentMap.get(cell.textContent)
        : [];
      // Push the current cell into the array.
      array.push(cell)
      // Store the array in the map.
      contentMap.set(cell.textContent, array);
  });

  // Create a color generator, it will create a random
  // color but never the same color twice.
  const 
    randomColor = colorGenerator();
    
  // Iterate over all the entries in the map, each entry is a unique 
  // cell content text
  contentMap.forEach(cells => {
    // When the lengths of the cells array is less than 2 it means 
    // it is not multiple times in the table. Exit now.
    if (cells.length < 2) {
      return;
    }
    
    // Generate a random color for the current content text. This is just
    // a very naive implementation. It doesn't make any promises on readability.
    const
      color = randomColor();
      
    // Apply the random color to all the cells with the same content.
    cells.forEach(cell => {
      cell.style.backgroundColor = color;
    });
  });
}

highlightDoubles(document.getElementById('sortable'));
<table id="sortable">
    <tbody>
        <tr>
            <td class="content">A</td>
        </tr>
        <tr>
            <td class="content">B</td>
        </tr>
        <tr>
            <td class="content">A</td>
        </tr>
         <tr>
            <td class="content">C</td>
        </tr>
         <tr>
            <td class="content">C</td>
        </tr>
    </tbody>
</table>

0
投票

每当你在if语句创建一个新的对象,像做

var rowComposite = new Object();
rowComposite.count = 1;
rowComposite.row = this;
var myColor = generateRandomColor();
rowComposite.color = myColor;

然后当你指定的颜色分配给它。颜色,而不是仅仅“红”:

$(rowComposite.row).css('backgroundColor', rowComposite.color);

你可以阅读有关颜色随机产生是js的位置:Random color generator


0
投票

您可以通过使用自定义功能,例如生成随机颜色为如下

$(function() {
    var tableRows = $("#sortable tbody tr"); //find all the rows
    var rowValues = []; //to keep track of which values appear more than once
    tableRows.each(function() { 
        var rowValue = $(this).find(".content").html();
        if (!rowValues[rowValue]) {
            var rowComposite = new Object();
            rowComposite.count = 1;
            rowComposite.row = this;
            rowValues[rowValue] = rowComposite;
        } else {
            var rowComposite = rowValues[rowValue];
            if (rowComposite.count == 1) {
                $(rowComposite.row).css('backgroundColor',getRandomColor());
            }
           // $(this).css('backgroundColor', getRandomColor());
           $(this).css('backgroundColor', 'red');
            rowComposite.count++;
        }
    });
});

function getRandomColor() {
  var letters = '0123456789ABCDEF';
  var color = '#';
  for (var i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  }
  return color;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="sortable">
    <tbody>
        <tr>
            <td class="content">A</td>
        </tr>
        <tr>
            <td class="content">B</td>
        </tr>
        <tr>
            <td class="content">A</td>
        </tr>
         <tr>
            <td class="content">C</td>
        </tr>
         <tr>
            <td class="content">C</td>
        </tr>
        <tr>
            <td class="content">C</td>
        </tr>
    </tbody>
</table>

0
投票
function random_rgba() {
    var o = Math.round, r = Math.random, s = 255;
    return 'rgba(' + o(r()*s) + ',' + o(r()*s) + ',' + o(r()*s) + ',' + r().toFixed(1) + ')';
}

$(function() {

    var tableRows = $("#sortable tbody tr"); //find all the rows
    var rowValues =  {}; //to keep track of which values appear more than once
    var color = "";
    tableRows.each(function() { 
        var rowValue = $(this).find(".content").html();
        if (rowValues[rowValue]){
            color = rowValues[rowValue];
        }else{
            color = random_rgba();
          rowValues[rowValue] = color;
        }
        $(this).css('backgroundColor', color);
    });
});

在这里你有它的工作:https://jsfiddle.net/zn0g9u34/9/


0
投票

你可以试试这个。简约时尚的外观:

$(function(){
    var st=document.createElement("style");
    document.head.appendChild(st);
    var sty={}, s;
    var A={}, cou=1;
    $("#sortable .content").each(function(i, c){
         if(!sty[c.innerHTML]){
            sty[c.innerHTML]=1;
            A[c.innerHTML]=cou++;
         }else sty[c.innerHTML]+=1;
         c.setAttribute("data-w", A[c.innerHTML]);
    });
    for(s in sty){
        if(sty[s]>1){
            st.sheet.insertRule("#sortable .content[data-w='"+A[s]+"']{background-color:rgb("+
                parseInt(Math.random()*256)+","+ 
                parseInt(Math.random()*256)+","+
                parseInt(Math.random()*256)+
            ");}", 0);
        };
    };
});

对不起,我有我的手机打字,我还没有获得小提琴。


Try it online!

© www.soinside.com 2019 - 2024. All rights reserved.