javascript - jQuery - 将元素添加到数组中

标签 javascript jquery arrays

我正在尝试将 ID 添加到一个数组中,这些 ID 是 html 跨度中的 $hexcode 值。我如何使用 jQuery 执行此操作?最终,我将需要获取这些十六进制代码值并将它们与颜色索引相匹配。

<?php
// display every color in the world

$r = 0;
$g = 0;
$b = 0;
$i = 0;
$step = 16;

for($b = 0; $b < 255; $b+=$step ) {
    for($g = 0; $g < 255; $g+=$step) {
        for($r = 0; $r < 255; $r+=$step) {
        $hexcolor = str_pad(dechex($r), 2, "0", STR_PAD_LEFT).str_pad(dechex($g), 2, "0", STR_PAD_LEFT).str_pad(dechex($b), 2, "0", STR_PAD_LEFT);
        echo '<span class="color_cell" id="'.$hexcolor.'" style="width: 5px; height: 5px; background-color:#'.$hexcolor.'; border: 1px dotted;">&nbsp;</span>'

        if($i%256 == 0) {
            echo "<br />";
        }
        $i++;
        }
    }

}
?> 
<script src="jquery-1.6.2.js"></script>
<script type="text/javascript">

var ids = [];

    $(document).ready(function($) {    
    $(".color_cell").bind('click', function() {
        alert('Test');
        //how do i add the ID (which is the $hexcolor into this array ids[]?
        ids.push($(this).attr('id'));       
    });
});

提前致谢!

最佳答案

试试这个,在每个循环结束时,ids 数组将包含所有十六进制代码。

var ids = [];

    $(document).ready(function($) {
    var $div = $("<div id='hexCodes'></div>").appendTo(document.body), code;
    $(".color_cell").each(function() {
        code = $(this).attr('id');
        ids.push(code);
        $div.append(code + "<br />");
    });



});

关于javascript - jQuery - 将元素添加到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6991313/

相关文章:

javascript - 获取 Google 电子表格的上次更新日期作为 JSON 端点

javascript - 如何传递在 jQuery 数据表中选中复选框的行列的值

php - 有 PHP -> jQuery 库吗?

java - android 夹板字符串

java - 如何删除数组合并方法中的重复项?

javascript - 强制发布请求在新页面加载之前完成提交

javascript - Ember.js 对象函数定义中的计算属性

jquery - 如何获取克隆元素的html

javascript - 使用里程表将变量传递给 jquery

javascript - Array.map 似乎不适用于未初始化的数组