JQuery $. each traverses the JavaScript array object instance, jquery. each

Source: Internet
Author: User
Tags tagname

JQuery $. each traverses the JavaScript array object instance, jquery. each

View a simple jQuery example to traverse a JavaScript Array object.

var json = [{"id":"1","tagName":"apple"},{"id":"2","tagName":"orange"},{"id":"3","tagName":"banana"},{"id":"4","tagName":"watermelon"},{"id":"5","tagName":"pineapple"}];$.each(json, function(idx, obj) {alert(obj.tagName);});

The code snippet above works normally and prompts "apple", "orange "... As expected.
Question: JSON string

In the following example, a json string (with a single or double quotation mark) is declared directly.

var json = '[{"id":"1","tagName":"apple"},{"id":"2","tagName":"orange"},{"id":"3","tagName":"banana"},{"id":"4","tagName":"watermelon"},{"id":"5","tagName":"pineapple"}]';$.each(json, function(idx, obj) {alert(obj.tagName);});

In Chrome, it displays errors in the console:

Uncaught TypeError: Cannot use 'in' operator to search for '000000'
In [{"id": "1", "tagName": "apple "}...

Solution: convert a JSON string to a JavaScript Object.
To fix it, convert it to a JavaScript Object through standard JSON. parse () or jQuery's $. parseJSON.

var json = '[{"id":"1","tagName":"apple"},{"id":"2","tagName":"orange"},{"id":"3","tagName":"banana"},{"id":"4","tagName":"watermelon"},{"id":"5","tagName":"pineapple"}]';$.each(JSON.parse(json), function(idx, obj) {alert(obj.tagName);});//or $.each($.parseJSON(json), function(idx, obj) {alert(obj.tagName);});
Reference: http://www.codes51.com/article/detail_641.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.