Domanda

So I have a modal. that when triggered fetches. 1 JSON file. The JSON has multiple nodes; however, I just want to target the last 4 nodes and omit anything before it. The name of these nodes are: post_a, post_b, post_c, post_d. They will always be the last 4 nodes in the array. That's the best logic I can think of :c

I'm at the very last interaction of my portfolio and I'm so stumped on how to traverse through just these 4 nodes. I understand that it will wonkey logic and I'm ok with this. I'm pretty far down the rabbit hole and now and I just want it to work. :(

Sample JSON file:

{
  created_at: "2013-07-15T05:58:25Z", 
  id: 21, 
  name: "Skatelocal.ly",
  svg: "<svg> ... </svg>",
  post_a: "This is an awesome post 1", 
  post_b: "This is an awesome post 2", 
  post_c: "this is an awesome post 3", 
  post_d: "this is an awesome post 4"
}

Here are the triggers as well as JSfiddle of how it should traverse:

JSFIDDLES


postInModal = function(data, status) {

  $(".next").on({
    click: function() {
    //jsfiddles has working interaction dont want to cludder  
    $(".modal-main").hide().html(data.post_X).fadeIn()
    }
  });
  return $(".prev").on({
    click: function() {
    //jsfiddles has working interaction dont want to cludder
    $(".modal-main").hide().html(data.post_X).fadeIn()
    }
  });
};
return popProject = function(x) {
  return $.ajax({
    type: "GET",
    url: "/works/" + x + ".json",
    success: postInModal
  });
È stato utile?

Soluzione

Something like this?

var keys = [ 'post_a', 'post_b', 'post_c', 'post_d' ];
$.each(keys, function(i, key) {
  var val = yourJsonObject[key];
  // do something with val ..  
});

To draw each value one after another:

var keys = [ 'post_a', 'post_b', 'post_c', 'post_d' ];
var index = 0;

function getNext() {
  if (index < keys.length) {
    var key = keys[index++];
    var val = yourJsonObject[key];
    return val;
  }
  return null;
}

In your click handler try

var val = getNext();
if (val != null) {
  // do something with value
} else {
  // we haven gotten everything already
  // do nothing or reset index to start again or whatever
}

Altri suggerimenti

You can try with this logic, traverse through JSON object to find value of post_* values, push into array object. Now this array object can be used to iterate when .next or .prev buttons are clicked

Traversing code is as below

       function js_traverse(o) {
            var type = typeof o;
            if (type == "object") {
                for (var key in o) {
                    if (key.indexOf("post_") >= 0)
                        print(o[key]);                        
                }
            } 
        }

If you have multiple of objects of type that you have specified in demo code, then you can use dimensional array object or so.

You can also check demo at this fiddle

Queries welcomed!

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top