How to pass an array into jQuery .data() attribute

前端 未结 4 2027
野的像风
野的像风 2020-12-13 03:39

Ok so I want to pass a very basic array into a jquery data attrubute server side like so:

<
相关标签:
4条回答
  • 2020-12-13 03:44

    Declaring it as an attribute means that it is a string.

    So stuff[0] would be equivalent to: var myString = "['a','b','c']"; alert(myString[0]);

    You need to make it look like this:

    <div data-stuff="a,b,c"></div>
    
    var stuff = $('div').data('stuff').split(',');
    alert(stuff[0]);
    

    Retraction: jQuery's parsing fails because it didn't meet the rules of parseJSON.

    However, I will stand behind my solution. There are aspects of the others that are less than ideal, just as this solution is less than ideal in some ways. All depends on what your paradigms are.

    0 讨论(0)
  • 2020-12-13 03:54

    A different approach is posted at jsfiddle; var stuff = $('div').data('stuff'); stuff is a string with 0th character as '['

    Well, var stuff = eval($('div').data('stuff')); should get you an array

    0 讨论(0)
  • 2020-12-13 03:55

    It's treating your variable as a string, the zeroth element of which is [.

    This is happening because your string is not valid JSON, which should use double-quotes as a string delimiter instead of single quotes. You'll then have to use single-quotes to delimit the entire attribute value.

    If you fix your quotation marks your original code works (see http://jsfiddle.net/ktw4v/12/)

    <div data-stuff='["a","b","c"]'> </div>
    
    var stuff = $('div').data('stuff');
    

    When jQuery sees valid JSON in a data attribute it will automatically unpack it for you.

    0 讨论(0)
  • 2020-12-13 04:00

    As others have identified the value is treated as string so it is returning "[". Please try this (aaa is the name of the div and I took out the data-stuff):

    $(function(){
        $.data($("#aaa")[0],"stuff",{"aa":['a','b','c']});
        var stuff = $.data($("#aaa")[0],"stuff").aa;
        alert(stuff[0]); //returns "a"
    });
    
    0 讨论(0)
提交回复
热议问题