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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6991313/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:09:47  来源:igfitidea点击:

jQuery - adding elements into an array

javascriptjqueryarrays

提问by Richard

I'm trying to add the ID's, which are the $hexcode values from the html span into an array. How do I do this with jQuery? Eventually, I'm going to need to grab these hexcode values and match them to a color index.

我正在尝试将 ID(即 html span 中的 $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'));       
    });
});

Thanks in advance!

提前致谢!

回答by ShankarSangoli

Try this, at the end of the each loop, ids array will contain all the hexcodes.

试试这个,在每个循环结束时,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 />");
    });



});

回答by Brook

var ids = [];

    $(document).ready(function($) {    
    $(".color_cell").bind('click', function() {
        alert('Test');

        ids.push(this.id);       
    });
});