문제

I have this HTML:

<section id="SSID" data-texts="'Text1', 'Text2', 'Text3'"></section>

I want to create an Array variable in jQuery and my jQuery code is:

$(document).ready(function() {
    var Selection = $("#SSID").data("texts");
    var Texts = [ Selection ];

    console.log(Texts.length);
});

For my example, the result I expect is:

Texts[0] = 'Text1'
Texts[1] = 'Text2'
Texts[2] = 'Text3'

...and that the length of the array Texts is 3.

However, what I am seeing is that the length of Texts is 1 and that the entire string is being loaded into Texts[0]:

Texts[0] = "'Text1', 'Text2', 'Text3'"

I think my problem is being caused by the " (quotation mark) characters. How can overcome this problem and achieve my objective?

도움이 되었습니까?

해결책 2

You can use JSON.parse()

HTML :

<section id="SSID" data-texts='"Text1", "Text2", "Text3"'></section>

JQUERY :

var Selection = JSON.parse('[' + $("#SSID").data("texts") + ']');

Fiddle Demo

or

HTML :

<section id="SSID" data-texts='"Text1", "Text2", "Text3"'></section>

JQUERY :

var Selection = JSON.parse($("#SSID").data("texts"));

FYI : But it would be better to store the actual JSON as the data attribute value. For eg : data-texts='["Text1", "Text2", "Text3"]' and parse it directly.


UPDATE : Or you can do it using Array#map method and String#split method.

var Selection = $("#SSID").data("texts").split(',').map(JSON.parse);

console.log(Selection);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<section id="SSID" data-texts='"Text1", "Text2", "Text3"'></section>

다른 팁

data- attributes can contain JSON.

jQuery will automatically parse them for you, if they are syntactically valid.

<section id="SSID" data-texts='["Text1", "Text2", "Text3"]'></section>

and

$(function() {
    var texts = $("#SSID").data("texts");

    console.log(texts.length);  // logs "3"
});

See: http://jsfiddle.net/5mtre/


Security hint: You must encode the JSON correctly on the server.

This means that you need to do JSON encoding and HTML encoding, here shown examplary using PHP:

<section id="SSID" data-texts="<?=htmlspecialchars(json_encode($data), ENT_QUOTES, 'UTF-8')?>"></section>
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top