1

我正在为我的选择表单使用 mobiscroll,并且在使用静态内容时没有问题,但是......

现在我正在尝试使用来自 ajax/json 的动态内容创建一个 mobiscroll。

这是我正在尝试做的事情:

$(document).ready(function(){

    $(function(){

        var all_friends = [];

        $.getJSON('http://mypage.com/json/friends.php', function(data){

            $.each(data, function (i, val) {
                all_friends.push("'1':'<div class='friend'><div class='profileimg'><img src='http://mypage.com/"+val.img+"'/></div><span>"+val.name+"</span></div>'");
            });

            var friendlist = {all_friends}; // THIS IS WHAT GIVES ME TROUBLE. I CANT DO THIS? //

            var wheel = [{}];
            wheel[0]['Choose friend'] = friendlist;

            $('#friends').scroller({
                display: 'bottom',
                mode: 'scroller',
                wheels: wheel,
                theme: 'ios',
                animate: 'fade',
                cancelText: 'Regret',
                setText: 'OK',
                height: 40,
                width: 280,
                formatResult: function(data){
                    return data;
                },
                onSelect: function(textValue, inst){
                    var returnData = textValue.toString();
                    var returnData = returnData.split(',');

                    var friend = returnData[0];

                    $('#friends').html(friend);
                }
            });
        });
    });
});

all_friends 数组返回:

'1':'<div class="friend"><div class="profileimg"><img src="http://mypage.com/someimage.png"/></div><span>Friend1</span></div>',
               '2':'<div class="friend"><div class="profileimg"><img src="http://mypage.com/someimage.png"/></div><span>Friend2</span></div>',
               '3':'<div class="friend"><div class="profileimg"><img src="http://mypage.com/someimage.png"/></div><span>Friend3</span></div>' 

我似乎无法在朋友列表的 {} 括号内获取数组?这是静态时的外观:

var friendlist = {'1':'<div class="friend"><div class="profileimg"><img src="http://mypage.com/someimage.png"/></div><span>Friend1</span></div>',
               '2':'<div class="friend"><div class="profileimg"><img src="http://mypage.com/someimage.png"/></div><span>Friend2</span></div>',
               '3':'<div class="friend"><div class="profileimg"><img src="http://mypage.com/someimage.png"/></div><span>Friend3</span></div>'}

希望提前帮助和感谢:-)

4

1 回答 1

0

以下代码应该适合您:

var friendlist = {}

$.each(data, function (i, val) {
   $.extend(friendist, {"1":"<div class='friend'><div class='profileimg'><img src='http://mypage.com/"+val.img+"'/></div><span>"+val.name+"</span></div>'"});
});

// here friendlist will be of the format you expect
于 2013-07-18T04:40:18.223 回答