【问题标题】:Not sure why jQuery isn't getting the variable information不知道为什么 jQuery 没有得到变量信息
【发布时间】:2011-08-16 19:32:02
【问题描述】:

这些值似乎没有出现并显示在页面上。它应该创建带有google_color 和背景设置为十六进制值的 div。

该应用程序假定获取像素图像数据并将其与我的名为 formatted_colors.js 的样本库相匹配,该库是一个数组。数组如下所示:

var colors = []; colors["000000"] = "black"; colors["100000"] = "black"; colors["200000"] = "black";

也许我不应该使用 .each 函数?虽然是个循环。

这是一个sn-p:

<div class="rounded_color" hex="<?php echo $css_color ?>" xy="<?php echo $x.$y ?>"></div>
<div id="<?php echo $x.$y ?>"></div>

<script type="text/javascript" src="jquery-1.6.2.js"></script>
<script src="formatted_colors.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">

//iterate through pixels and match rounded color to array in formatted_colors.js

$(document).ready(function() {

    $(".rounded_color").each(function(){ 
            var google_color = getColor($(this).attr("hex")); // finds a match of "hex" value in formatted_colors.js and return name to google_color
            $('#'+$(this).attr("hex")).html(google_color); // set the div's html to name which is google_color
            alert('#'+$(this).attr("id")); //testing if value is there, but shows #undefined
            $('#'+$(this).attr("hex")).css('background-color:', google_color); 
    })


// get name of color function from formatted_colors.js

function getColor(target_color){
    if (colors[target_color] == undefined) { // not found
      return "no match";
    } else {
      return colors[target_color];
    }
  } // end getColor function


}) // end ready function

</script>

抱歉,我是新手,所以我不确定现在该做什么。

这是我的完整代码:http://pastebin.com/HEB3TWZP

提前致谢!

【问题讨论】:

  • formatted_colors.js 中的颜色数组在哪里设置?如果您将其设置在 $(document).ready() 函数中,那么我的猜测是当您尝试在此文件中访问它时,您的变量范围存在问题。另外,我认为使用 .css() 设置背景颜色时不需要冒号。

标签: php javascript jquery syntax


【解决方案1】:

您不需要连接#this 是迭代中的当前元素。

您还可能想做var $this = $(this); 之类的操作,清理您的代码,并且您不会在同一迭代中一遍又一遍地重新创建 jQuery 对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-10
    • 2019-11-12
    • 1970-01-01
    • 2022-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多