开发者

JQuery JSON - Using variables

OK let's say I have this:

开发者_运维技巧<!DOCTYPE html>
<html>
<head>
  <style>img{ height: 100px; float: left; }</style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <div id="images">
Hello<br />
</div>
<script>
$.getJSON("main.txt",
  function(data) {
    var getTitle = title;    
    $.each(data.getTitle, function(i,getTitle){
       $("#images").append(getTitle);
    });
  });</script>
</body>
</html>

it doesn't work because of var getTitle = title. I know that. But if I take out the var and replace getTitle with title which is INSIDE the JSON file.. it WILL work. But I don't want to edit three pieces of title for each code so I just make a variable so I can edit all three at once... but it doesn't work...


Instead of accessing the object as data.getTitle, try using [].

var getTitle = "title";
$.each(data[getTitle], function(........)

This would solve the problem.


I just make a variable so I can edit all three at once

That doesn't make any sense. The name of the variable doesn't matter at all. For what you're doing, this works just as well:

$.getJSON('main.txt', function(data) {
    $.each(data.title, function(i, anyVariableNameILikeGoesHere) {
        $('#images').append(anyVariableNameILikeGoesHere);
    });
});

However, jQuery actually provides a more concise way of writing this:

$.getJSON('main.txt', function(data) {
    $.each(data.title, function() {
        $('#images').append(this);
    });
});

Aside from that though, why are you iterating over data.title? Looking at your json, it's a single string! This is a much better way to write it:

$.getJSON('main.txt', function(data) {
    $('#images').append(data.title);
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜