使用Jquery切换Json对象的值

时间:2014-04-24 16:05:33

标签: javascript jquery json toggle

我有一个任务列表,可以从json对象中获取4种可能的状态。

"Not Done", "Done", "Doing", "Later"

这种状态存储在一个基本上通过json加载的对象中。

var states = {  status: ['doing','done', 'later' ]  };

从另一个json对象加载任务。

var tasks = [
    {id: 1, text: 'Do something.', status: 'doing'},
    {id: 2, text: 'Undo that thing.', status: 'done'},
    {id: 3, text: 'Redo it again.', status: 'started'},
    {id: 4, text: 'Responsive', status:'later'}
  ];

html会是这样的。

<ul>
<li><a href="#1">Do something - <span class="status">Doing</span> </a></li>
<li><a href="#2">Undo that thing - <span class="status">Done</span> </a></li>
<li><a href="#2">Redo it again. - <span class="status">Started</span> </a></li>
</ul>

每次用户点击链接时,状态都应该从states对象切换值 并循环它们。例如,当使用点击status Done的任务时,它应该变为later,当他们再次点击时,它应该变为Not Done。每次用户点击时都应该保持循环。

这样做的最佳方法是什么。我觉得如果不是正确的做法,就好像国家的价值增加或减少,那么代码将不得不再次重新审视。

2 个答案:

答案 0 :(得分:1)

编辑:

我不明白你问题的100%。但我想我现在这样做。您希望代码始终在所有情况下都能正常工作。我现在让代码更安全一些:

  • 如果状态包含输入错误的文本(如'dOne'),它仍会比较。
  • 如果任务有错误(=不存在)状态,它只会将自身重置为第一个可用状态。

这是一个代码爆炸,我有点累,所以你可能需要重构一些部分。还认为包含文档会更容易。

如果您有更多要说的话,请将其留在评论中,我会再试一次....!

工作jsfiddle:http://jsfiddle.net/kychan/62sUX/2/

//
//    Retrieve the data with $.get()/AJAX or with an inline
//    echo through PHP/ASP.
//

//    Get states. Make the code extra fuzzy.
var states = {  status: ['doing','dOne', 'Later' ]  };

//    Get the tasks.
//    In this example we do it more quickly.
var tasks = [
    {id: 1, text: 'Do something.',     status: 'doing'},
    {id: 2, text: 'Undo that thing.',  status: 'done'},
    {id: 3, text: 'Redo it again.',    status: 'started'},
    {id: 4, text: 'Responsive',        status: 'later'}
];

//    prepare the retrieved JSON data for fuzzy input.
states.status.forEach(function(e,i,a) {
    states.status[i]=e.toUpperCase();
});
tasks.forEach(function(e,i,a) {
    tasks[i].status=e.status.toUpperCase();
});

//    create the li's.
for (var i in tasks) {
    var item = '<li>'
             + '<a href="#" id="{id}">{text} - '
             + '<span class="status">{status}</span>'
             + '</a>'
             + '</li>'
    ;

    item    = item.replace(/{(\w+)}/g, function (m, n) {
        return (typeof (tasks[i][n]) !== 'undefined') ? tasks[i][n] : '';
    });

    $('ul').append(item);
}

//    Override the states with the button; will make it harder
//    for the code and test it for future proofness.
$('.replace').click(function() {
    //    we will keep 'done' for testing.
    states = {
        status:['CONCEPT', 'ELABORATION', 'CONSTRUCTION', 'TESTING', 'PRODUCTION', 'DONE']
    };
    //    remove the replace link, because after press it's useless.
    $('.replace').detach();
});

//
//    actual code.
//

//    create listeners on the a tags of tag ul.
$('ul a').click(function (e) {
    //    fetch status DOM object and its text before.
    var status = $(this).children('.status');
    var text   = status.html();

    //    iterate through states array.
    for (var i in states.status) {
        //    if the task matches your text, then update it to the next.
        if (text==states.status[i]) {
            //    get next status.
            if ((i++)>=states.status.length-1)  i=0;

            //    update. Don't forget to push the update to the database.
            status.html(states.status[i]);
            return;
        }
    }
    //    state not found. reset it to first. Don't forget to push the update to the DB.
    status.html(states.status[0]);
});

答案 1 :(得分:0)

这样的事情怎么样?

$('a').click(function(){
  var id = parseInt($(this).attr('href').substring(1));
  var task = tasks.filter(function(t){t.id == id});
  if (task.length) {
    var status = task[0].status;
    var indexStatus = states.status.indexOf(status);
    var nextStatus = null;
    if (indexStatus === states.status.length-1) {
      nextStatus = states.status[0];
    } else if (indexStatus !== -1) {
      nextStatus = states.status[indexStatus+1];
    }
    if (nextStatus !== null) {
      task[0].status = nextStatus;
      $(this).children('.status').text(nextStatus);
    }
  }
});

我们的想法是在列表中查找当前状态,如果它是最后一个,只需将索引重置为0,否则将其递增。

我已经更新了JSON和HTML,因为如果你想让它们同步,你就不精确了。如果您不需要同步数据和查看,则可以使代码更简单。我还做了所有必要的绑定检查,我不知道你想要代码的强大程度以及你对json数据的信任程度。