单独的div上的JQuery和Dynamic子列表

时间:2012-09-22 08:30:05

标签: javascript jquery

我正在尝试创建一个与典型的笼子页面分开的子列表视图页面:

这就是我要做的事情:

STEP1 - 循环获取所有数据并在列表视图中创建列表:

$(document).ready(function() {

     var data = {"id":[{"id":1,"title":"title1","bodytext":"sometext 1"},{"id":2,"title":"title2","bodytext":"sometext 2"},{"id":3,"title":"title3","bodytext":"sometext 3"}
                   }]

    var output = ''

    $.each(data.id, function(index, value){

       output += '<li><a href="#mypage">'+value.title+'</a></li>';

       $('#mypage').text(value.title); //will this be different for each item?

    });

    $('#mylistview').html(output).listview('refresh'); //Refresh the listview with new added data

});

第2步:

listview现在看起来像这样:

<ul id-"mylistview">
   <li><a href="populate_#mypage_with_data_from_item_1">title1</a></li>
   <li><a href="populate_#mypage_with_data_from_item_2">title2</a></li>
   <li><a href="populate_#mypage_with_data_from_item_3">title3</a></li>
</ul>

第3步:

我有一个预先制作的模板:

<div id="mypage">
Data from selected item goes here
</div>

So, if I click on list item 1 mypage will look like this:

<div id="mypage">
Sometext 1
</div>

or if item 2 is clicked:

<div id="mypage">
Sometext 2
</div>

我的问题是无论我在listview中点击哪个项目,我总是从第1项中获取数据。

我如何制作它以使每个项目都显示自己的数据?

2 个答案:

答案 0 :(得分:1)

$(document).ready(function() {
    var data = {"ids":[
         {"id":1,"title":"title1","bodytext":"sometext 1"},
         {"id":2,"title":"title2","bodytext":"sometext 2"},
         {"id":3,"title":"title3","bodytext":"sometext 3"}]};

    var output = '',
        myPages = $('.mypage'),
        container = $('#mylistview');

    $.each(data.ids, function(index, value){
       output += '<li><a href="#mypage">'+value.title+'</a></li>';
       myPages.eq(index).text(value.bodytext);
    });

    container.html(output);

    container.on('click', 'a', function(e){
        e.preventDefault();
        var links = container.find('a');
        alert(myPages.eq(links.index(this)).text());
    });
}); 

演示:http://jsfiddle.net/mDnE6/

答案 1 :(得分:0)

那是因为你只能有一个id调用“pagetitle”