如何在JQuery中将字符串作为数组对象

时间:2011-01-22 13:29:05

标签: jquery

我在变量中得到了以下字符串值。

var mystring = '{"img_src":"/english/images/spa.jpg",
    "img_title":"Enjoy a refreshing shower at 43,000 feet",
    "img_alt":"Enjoy a refreshing shower at 43,000 feet",
    "img_height":"326",
    "img_width":"980",
    "header":"Enjoy a refreshing shower at 43,000 feet",
    "subheader":"One of many groundbreaking amenities",
    "bg_color":"",
    "url_href":"1"}, 
     {"img_src":"/english/images/spa1.jpg",
    "img_title":"Enjoy a refreshing shower at 43,000 feet",
    "img_alt":"Enjoy a refreshing shower at 43,000 feet",
    "img_height":"326",
    "img_width":"980",
    "header":"Enjoy a refreshing shower at 43,000 feet",
    "subheader":"One of many groundbreaking amenities",
    "bg_color":"",
    "url_href":"1"}'

现在我想将此字符串变量转换为Array对象。因此,如果我尝试访问它我的函数它应该像一个数组对象。例如。

some code to Convert(mystring) to an Array Object(myArryObject),然后我想将它传递给我的函数,如下所示

$.fn.liveBanner = function(myArryObject,optional_options) 
    { 
      //here I want to access my myArryObject as below
      alert(myArryObject[0].img_src) //then it should give "/english/images/spa.jpg"
});

请建议使用JQuery。

修改

我按照@Deceze的建议进行了更改,请参阅下文:

             var myString = "'"+ $("#RotationImages #mainHidden").attr("value")+"'";     

    var myArrayobj = jQuery.parseJSON('[' + myString + ']');
    alert(myArrayobj.img_src);

上面的代码给出了以下错误

Error: uncaught exception: Invalid JSON:'{"img_src":"/english/images/spa.jpg", "img_title":"Enjoy a refreshing shower at 43,000 feet","img_alt":"Enjoy a refreshing shower at 43,000 feet", "img_height":"326","img_width":"980","header":"Enjoy a refreshing shower at 43,000 feet","subheader":"One of many groundbreaking amenities on the Flight","bg_color":"","url_href":"1"}'

7 个答案:

答案 0 :(得分:1)

由于您的字符串只包含数组中的对象,因此您必须在解析之前添加数组声明:

var myArrayobj = jQuery.parseJSON('[' + myString + ']');

答案 1 :(得分:1)

根据定义的mystring,执行var myArray = jQuery.parseJSON('[' + mystring } ']');将产生一个对象数组。有关实例,请参阅this jsfiddle

您获得无效JSON错误的原因是您将有效JSON包装在单引号中,从而使其无效。也就是说,第一行:

var myString = "'"+ $("#RotationImages #mainHidden").attr("value")+"'";     

var myArrayobj = jQuery.parseJSON('[' + myString + ']');
alert(myArrayobj.img_src);

使您的JSON无效。第一行应该是(假设值正确):

var myString = $("#RotationImages #mainHidden").attr("value");

有关JSON的详细信息,请参阅json.orgRFC 4627

答案 2 :(得分:0)

嗯,首先,你的输入有type =“hidden”,这意味着无论你在周围的div上运行什么jQuery,这些元素都不会出现。如果您的边界div具有“display:none”,则没有理由将输入类型设置为隐藏。

您确实需要修改编写此代码的方式。你应该有一个样式表来隐藏图像(你应该将它们放在代码中作为图像),然后你可以使用javascript来显示它们。您可以使用jQuery UI Tabs演示作为指导如何正确构建标记,然后从那里开始。

您是否有特定原因使用输入图像?

答案 3 :(得分:0)

好的,你还没有朝着正确的方向前进。

您的jQuery具有以下内容:

.attr('type','hidden').

此段将类型设置为隐藏。然后,您将输出写入屏幕。

将其更改为:

.attr('type','image').

看看是否有所作为(你必须创建一个未设置的函数,当你完成后将它改回“隐藏”)。

就像我说的那样,这实际上并不是你做的事情最干净的方式,但除了建议你再尝试使用不同的方法之外,我不能指出任何其他方式。

答案 4 :(得分:0)

最后我能够写一些JQuery来帮助我解决我的问题,现在我能够得到我想要的HTML。下面是JQuery代码,请查看并告诉我任何改进。

$(document).ready(function()
{
        var rotationImagelength = $('#RotationImages input[type=hidden]').length; //Getting the length of the Rotation Image Input type hidder
        var ImageDetail; 
        var $addDetails="";
        var fromPageInput = $("<input>").attr("id", "mainHidden").attr("type", "hidden").attr("name", "fromPage").val(ImageDetail); //Generating the dynamic input type hidden  

        $('#RotationImages input[type=hidden]').each(function(index,element) //Loop for all the input type hidden in RotationImage DIV
        {   

            if(index != rotationImagelength - 1) //Loop for checking not the last input hidden, we are adding extra Comma(,)
            {                    
                ImageDetail = '{"img_src":"'+ $(element).attr("src")+'", "img_title":"'+ $(element).attr("title")+'","img_alt":"'+ $(element).attr("alt")+'", "img_height":"'+ $(element).attr("height")+'","img_width":"'+ $(element).attr("width")+'","header":"'+ $(element).attr("header")+'","subheader":"'+ $(element).attr("subheader")+'","bg_color":"'+ $(element).attr("color")+'","url_href":"'+ $(element).attr("href")+'"},';                                                  
                $addDetails += ImageDetail;
            }    
            else //Generating HTML for the last input hidden
            {
                ImageDetail = '{"img_src":"'+ $(element).attr("src")+'", "img_title":"'+ $(element).attr("title")+'","img_alt":"'+ $(element).attr("alt")+'", "img_height":"'+ $(element).attr("height")+'","img_width":"'+ $(element).attr("width")+'","header":"'+ $(element).attr("header")+'","subheader":"'+ $(element).attr("subheader")+'","bg_color":"'+ $(element).attr("color")+'","url_href":"'+ $(element).attr("href")+'"}';                                                            
                $addDetails += ImageDetail;
            }                

            $(fromPageInput).val($addDetails); //Adding full values in the dynamic input hidden created above    


        });
         $("#RotationImages").append($(fromPageInput)); //Appending to the RotationImage DIV so that we can easily use in JQuery.
         var test = ($("#RotationImages #mainHidden").attr("value"));
         alert(test);
});

感谢您的帮助,我们随时欢迎您的建议

答案 5 :(得分:0)

你需要使用javascript var(我认为):

gImgs = [
    {"img_src":"/english/images/spa.jpg",
    "img_title":"Enjoy a refreshing shower at 43,000 feet",
    "img_alt":"Enjoy a refreshing shower at 43,000 feet",
    "img_height":"326",
    "img_width":"980",
    "header":"Enjoy a refreshing shower at 43,000 feet",
    "subheader":"One of many groundbreaking amenities",
    "bg_color":"",
    "url_href":"1"}
];

然后

$('.slideshow').liveBanner(gImgs, {"autostart":false, 
  "pause_time":5500, "random":false});

因此,在每个页面上,您将拥有不同的gImgs。请注意,如果您为liveBanner创建添加了脚本,则必须在gImgs之前定义<script src="..."></script>,例如:

<html>
    <head>
        <!-- ... -->
        <script type="application/x-javascript">
        <!--
            var gImgs = [ /* ... */ ];
        -->
        </script>
        <script type="application/x-javascript" src="yourscript.js"></script>
    </head>
    <body>
    <!-- ... -->
    </body>
</html>

答案 6 :(得分:0)

尝试jQuery.parseJSON