2013-02-17 179 views
1

我試圖從初始位置到其它位置動畫一些div。JavaScript字符串和對象數組

對於這一點,我從這個小提琴適應代碼:

http://jsfiddle.net/c6UEm/27/

我的代碼是:

function animate(list, lft, top, callback) { 

alert('list: '+list); 

if (list.length === 0) { 
    callback(); 
    return; 
} 
$el = list.shift();   // div ids 
var lll = lft.shift(); // new value for left of this div (from lft array) 
var ttt = top.shift(); // new value for top of this div (from top array) 
$el.animate({"left": +lll+'px', "top": +ttt+'px'}, 1000, function() { 
    animate(list, lft, top, callback); 
}); 
} 

如果我硬編碼 '列表'(div編號)如下;

 $('#TDA0mv'),$('#TDA1mv'),$('#TDA2mv'),$('#TDA3mv'),$('#TDA4mv'),$('#TDA5mv'),$('#TDA6mv'),$('#TDA7mv'),$('#TDA8mv') 

以上的警報產生這個;

list: [object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object] 

它根據需要工作。

如果我檢索來自一個隱藏字段的ID,並建立一個數組(或甚至一個字符串,它然後分裂)我有此;

  $('#TDA0mv'),$('#TDA1mv'),$('#TDA2mv'),$('#TDA3mv'),$('#TDA4mv'),$('#TDA5mv'),$('#TDA6mv'),$('#TDA7mv'),$('#TDA8mv') 

這在上述警報呼叫:

list:$('#TDA0mv'),$('#TDA1mv'),$('#TDA2mv'),$('#TDA3mv'),$('#TDA4mv'),$('#TDA5mv'),$('#TDA6mv'),$('#TDA7mv'),$('#TDA8mv') 

當然,這是行不通的。

有任何人任何想法,爲什麼看似相同的數據對象是如此的不同?我懷疑這可能是一個JSON類型的東西,因爲許多'類似'的查詢都是這樣回答的。然而,在這個方向上嘗試了幾件事情後,我似乎仍然以字符串而不是「對象」結束。

+1

請格式化你的代碼示例 – kirugan 2013-02-17 16:02:46

+1

請更新小提琴,以顯示你是如何的例子「從一個隱藏字段檢索ID和創建數組」 – 2013-02-17 16:04:12

+1

另外,請使用描述性變量名稱。如果你希望其他人能夠閱讀並幫助你使用你的代碼,那麼lll和ttt不是很好的變量名稱。 – 2013-02-17 16:06:48

回答

1

您還沒有解釋如何傳遞ID,但你不能只用<input type="hidden" value="$('#id')" />,因爲它會被解釋爲文本而不是jQuery對象。

你可以這樣做:http://jsfiddle.net/c6UEm/28/

<body> 
    <div id="container"> 
    <div id="one" class="box"></div> 
    <div id="two" class="box"></div> 
    <div id="three" class="box"></div> 
    </div> 
    <!-- Create an input field--> 
    <input type="hidden" id="list" value=""/> 
</body> 

$(document).ready(function() { 
    //Assign id values 
    $('#list').val('one,two,three'); 

    //Pass the list to your function 
    animate($('#list').val().split(','), finished); 
}); 

function finished() { 
    $('body').append('Finished'); 
} 

function animate(list, callback) { 
    if (list.length === 0) { 
     callback(); 
     return; 
    } 

    //Use id to use with JQuery 
    $el = $('#' + list.shift()); 
    $el.animate({left: '+=200',top: '-=10'}, 1000, function() { 
     animate(list, callback); 
    }); 
}