开发者

How to select a list item and show the details dynamically?

开发者 https://www.devze.com 2023-01-27 06:10 出处:网络
Im using jQTouch to make a mobile version of my website, and i need some help. Im using html5 storage feature. I have a list of jobs and I want to click on one job, and shows that job information in

Im using jQTouch to make a mobile version of my website, and i need some help.

Im using html5 storage feature. I have a list of jobs and I want to click on one job, and shows that job information in another div.

This is my code:

var uid;
var job_name;

for (var i=0; i<results.rows.length; i++) {    
var row = results.rows.item(i);

uid  开发者_开发问答= row['id'];
job_name   = row['job_name'];

$("ul#my_jobs").append('<li class="arrow" id="job_' + uid +'"><a class="fade" href="#prueba">' + job_name + '</a></li>');


$("li#job_" + row['id']).bind('tap', function(){
    $("#job_detail").html(row['id']);
});
}

The jobs are listing ok, but when I tap on one of them, always shows the last job.

Thanks!


It should look like this (without changing your layout too much):

var uid, job_name;
for (var i=0; i<results.rows.length; i++) {    
  var row = results.rows.item(i);
  uid  = row['id'];
  job_name   = row['job_name'];

  $("ul#my_jobs").append('<li class="arrow" id="job_' + uid +'"><a class="fade" href="#prueba">' + job_name + '</a></li>');
  (function(id) {
    $("li#job_" + id).bind('tap', function(){
      $("#job_detail").html(id);
    });
  })(uid)
}

JavaScript doesn't have block scope here, so that row variable, even though it's inside the for loop, is scope to the entire function, and it gets replaced each iteration...and ends up being the last value (which is why you see the last id each time).

A slimmed down version taking advantage of this new scope would be:

for (var i=0; i<results.rows.length; i++) {    
  var row = results.rows.item(i);
  (function(uid, job_name) {
    $('<li class="arrow" id="job_' + uid +'"><a class="fade" href="#prueba">' + job_name + '</a></li>').bind('tap', function(){
      $("#job_detail").html(uid);
    }).appendTo("#my_jobs");
  })(row['id'], row['job_name']);
}

This declares those other uid and jod_name variables only where they're needed, and eliminated the extra traversal inside the loop (finding the <li> you just created).

0

精彩评论

暂无评论...
验证码 换一张
取 消