开发者

Select JavaScript array element item with jQuery selectors

I have some json and jQuery doesn't seem to select its elements correctly. The json document I am referencing is available here: http://pastebin.com/bM3BvD2F.

the json is a array of elements and I'm trying to select one with required ID.

(you can copy-paste to http://jsonviewer.stack.hu/ for a nice folded view of it)

Here's the code I have problems with:

    //get current picture ID - will return '2' - correct value    
    var currentID = window.location.hash ? window.location.hash.substring(1) : allImages[0]["id"];

    //this line will alert name attribute va开发者_运维问答lue for a picture with (id = 4) - wrong :(
   alert($(allImages[id=currentID])[0].name);


allImages is a plain array, so allImages[id=currentID] will cause temp variable called id to be created, assigned the value of currentID and return 2, causing the third element in the array to be returned. This element has indeed id of 4.

What you need is "deep search" and one way to do this is using the .map function:

var name = jQuery.map(allImages, function (value) {
    return (value.id == currentID) ? value : null;
})[0].name;

Quick test case: http://jsfiddle.net/PWPcE/


Try:

alert($(allImages[id=currentID]).attr('name'));

I think by selecting the 0th element, you are selecting the 1st character from the answer you want.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜