Setting values to the td tag of the color grid using jquery

时间:2016-04-04 17:23:05

标签: jquery html

I have a color grid whose colors get shuffled each time when i run the program.I also have variables with some specific values (red=2,blue=3,green=4,yellow=1,orange=5,black=1,brown=6,pink=5).Now I want these values to be assigned to the td tag of the color grid by finding its color. Html:

<table  border="5px" width="500px" height="50px" align="center">
<tr id="colors">
<td height="50px" orderId="1" bgcolor="red"></td>
<td height="50px" orderId="6" bgcolor="brown"></td>

<td height="50px" orderId="5" bgcolor="pink" ></td>
<td height="50px" orderId="0" bgcolor="blue" ></td>

<td height="50px" orderId="7" bgcolor="black"></td>
<td height="50px" orderId="2" bgcolor="green"></td>

<td height="50px" orderId="4" bgcolor="orange" ></td>
<td height="50px" orderId="3" bgcolor="yellow"></td>
</tr>  
</table>

jQuery: Here the shuffling of colors is done and the color at each cell is found when shuffled.

$(function() {
    var arr = [];
    var colorCells = document.getElementById('colors').getElementsByTagName('td');
    var colors = ["blue","red","green","yellow","orange","pink","brown","black"];
    for(var i = 0; i < colorCells.length; i++)
    {
        colorCells[i].style.backgroundColor = colors.splice(Math.random() * (colors.length),1);
        arr.push(colorCells[i].style.backgroundColor);//finds the color of each cell
    }
    alert(arr);
});

Now I want these values to get assigned to the color grid Demo: https://jsfiddle.net/pckshu27/5/

1 个答案:

答案 0 :(得分:0)

Working fiddle : https://jsfiddle.net/pckshu27/3/

here to achieve your requirement, you need to add up one additional block under JS and a minor change under present JS.

Use of this $(colorCells[i]).attr("bgColor", colors.splice(Math.random() * (colors.length),1)) ; instead of colorCells[i].style.backgroundColor = colors.splice(Math.random() * (colors.length),1);

The above change has to be done, because using bgcolor under style tag, retrieval makes difference, as it returns under RGB format of color code, so instead you can use bgColor an attribute under TD, this makes easy retrieval and without change.

Additional JS block

var colorValues = {"red": 2, "blue":3, "green": 4, "yellow":"", "orange":5, "black":1, "brown":6, "pink":5};
$("table td").each(function() {
    $(this).html(colorValues[$(this).attr("bgColor")]);
});

the above code considers of an array with required keys and values, and pretty simple to be known, as if the attr bgColor value is red, it finds the key under the array, adds the value of Array[red] as the html under the TD. you can even use .text() instead of .html()