【问题标题】:Get values out of an array and create for each value a variable从数组中获取值并为每个值创建一个变量
【发布时间】:2012-08-16 13:14:21
【问题描述】:

我有这个 html:

<div id="h101" data-stellar-ratio="6"><img src="images/h1_01.png" width="600"></div>
<div id="cloud01" data-stellar-ratio="0.5"><img src="images/cloud_01-s.png"></div>
<div id="cloud02" data-stellar-ratio="0.4"><img src="images/cloud_01-s.png"></div>
<div id="island01" data-stellar-ratio="2"><img src="images/island_01.png" width="620"></div>

我从所有的 id 中创建一个数组

$(".section > div").each(function() {
ellementArray.push($(this).attr("id"));});

现在我的 ellementArray 中有所有值。 我想做的是创建这个:

var h101Left = $("#h101").position().left;
var cloud01Left = $("#cloud01").position().left;
var island02Left = $("#island02").position().left;
var island03Left = $("#island03").position().left;

我在想这样的事情......

for (var i = 0; i < ellementArray.length; i++){
        jQuery.globalEval("var ellementArray[i] = ellementArray[i];")
        console.log(ellementArray[i]);
    }

有人可以帮忙吗?

【问题讨论】:

    标签: jquery arrays variables


    【解决方案1】:

    你把事情复杂化了。只需创建一个从字符串(元素 ID)到数字(位置左值)的映射:

    var leftPositions = {};
    $(".section > div").each(function ()
    {
        leftPositions[this.id] = $(this).position().left;
    });
    

    顺便说一句,如果您仍然需要所有 ID 的数组,请使用 .map() 而不是 .each()this.id instead of $(this).attr('id')

    var elementArray = $(".section > div").map(function ()
    {
        return this.id
    }).get();
    

    【讨论】:

    • 很好的解决方案,但我的输出将是:h101 = 200;我需要的是 h101left = 200...
    • 好的,所以将leftPositions[this.id] 更改为leftPositions[this.id + 'left']。不是火箭科学。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多