Jquery .click函数访问特定对象

时间:2016-11-15 12:10:34

标签: jquery object click

如果我有一个对象列表并使用.append()将每个对象标题显示为li,当我单击要访问的对象并将整个对象附加到我的页面上时,我的对象如下所示: / p>

var object = {
"post1" : {
    "title" : "title1",
    "content" : "blllsd",
    "image" : "http://lorempixel.com/400/200/",
     "latest" : false
 },
"post2" : {
    "title" : "title2",
    "content" : "blalbvlasd",
    "image" : "http://lorempixel.com/700/200/",
     "latest" : true
},
"post4" : {
    "title" : "title3",
    "content" : "bla",
    "image" : "http://lorempixel.com/900/400/",
     "latest" : false
    }
};

jquery的:

    var result = $("#result");

    for (var key in object) {
    if (!object.hasOwnProperty(key)) continue;
    var element = object[key];
    };

var side = $("ul");
var  latest = $("#latest")
side.append("<li class='side'>" + element.title + "</li>");

$(".side").click(function() {
     for (var i=0; i<element.length; i++) {
          latest.prepend( element[i].title + element[i].content + element[i].image); 
        };
   };

这不打印任何东西,我不知道该怎么做。我读过这个类似的帖子,但我没有解释我的问题,并且我认为或者只是我很难理解,所以如果专家可以帮助那将是很棒的。 JavaScript closure inside loops – simple practical example 我和'#39;这个&#39;但没有进展。

1 个答案:

答案 0 :(得分:1)

您可以按照代码段中所示进行访问。 您可以将该对象的key存储到li

&#13;
&#13;
var object = {
"post1" : {
    "title" : "title1",
    "content" : "blllsd",
    "image" : "http://lorempixel.com/400/200/",
     "latest" : false
 },
"post2" : {
    "title" : "title2",
    "content" : "blalbvlasd",
    "image" : "http://lorempixel.com/700/200/",
     "latest" : true
},
"post4" : {
    "title" : "title3",
    "content" : "bla",
    "image" : "http://lorempixel.com/900/400/",
     "latest" : false
    }
};
var result = $("#result");

var side = $("ul");
var  latest = $("#latest")
for (var key in object) {
  if (!object.hasOwnProperty(key)) continue;
  var element = object[key];
  side.append("<li class='side' key='" + key + "'>" + element.title + "</li>");
};

$(".side").click(function() {
     var key = $(this).attr("key").trim();
    var obj = object[key]; //use this object data to populate your html
  $(result).html(JSON.stringify(obj));
  //console.log(obj);
   });
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<ul></ul>

<pre id="result"></pre>
&#13;
&#13;
&#13;