sourcetip

Store and retrieve JavaScript arrays into and from HTML data attributes

fileupload 2023. 10. 30. 21:13
반응형

Store and retrieve JavaScript arrays into and from HTML data attributes

How can a JavaScript array be stored in an HTML custom data attribute?

I've tried every variation of JSON stringification and escaping characters.

What is the precise method to store the array and retrieve it again?

저는 다음과 함께 어레이를 구축합니다.[ $("#firstSelectedElement").val(), $("#secondSelectedElement").val() ]. 검색합니다.id="storageElement" data-storeIt="stuff"와 함께$("#storageElement").data('storeit').

I can never seem to retrieve the data as a true array, only an array of characters.

요소에 HTML 이스케이프 문자를 사용할 수 있습니다.dataJSON-like 배열(인코딩된 따옴표)을 갖는 특성:

<div id="demo" data-stuff='[&#34;some&#34;, &#34;string&#34;, &#34;here&#34;]'></div>

And then in JavaScript get it without any additional magic:

var ar = $('#demo').data('stuff');

See this JSFiddle demo.

However, escaping isn't necessary. You can do this, instead:

<div id="demo" data-stuff='["some", "string", "here"]'></div>

See this JSFiddle demo.

It depends on what type of data you're storing in the array. If it's just strings (as it appears to be) and you have a character that you know will never be a part of your data (like the comma in my example below) then I would forget about JSON serialization and just use string.split:

<div id="storageElement" data-storeIt="stuff,more stuff"></div>

Then when retrieving:

var storedArray = $("#storageElement").data("storeIt").split(",");

JSON을 사용하는 것보다 조금 더 잘 다룰 것입니다.보다 적은 문자를 사용하고 "가격"이 저렴합니다.JSON.parse.

But, if you must, your JSON implementation would look something like this:

<div id="storageElement" data-storeIt='["hello","world"]'></div>

And to retrieve:

var storedArray = JSON.parse($("#storageElement").data("storeIt"));

이 예에서는 준인용을 사용해야 했습니다.') 주변에data-storeIt소유물.이것은 JSON 구문이 데이터의 문자열을 중심으로 따옴표를 사용하도록 요구하기 때문입니다.

HTML5 데이터 속성은 문자열만 저장할 수 있으므로 배열을 저장하려면 배열을 직렬화해야 합니다.JSON은 잘 될 것이고 당신은 옳은 길을 가고 있는 것 같습니다.당신은 단지 사용하기만 하면 됩니다.JSON.parse()직렬화된 데이터를 가져오면 다음을 수행합니다.

var retrieved_string = $("#storageElement").data('storeit');
var retrieved_array = JSON.parse(retrieved_string);

Reviewing the api documentation, jQuery should try to automatically convert a JSON encoded string provided it is properly encoded. Can you give an example of the value you are storing?

또한 HTML5 data attribute 와 jQuery 를 참고합니다..data()메소드는 두개의 구별되는 것입니다.상호작용을 하지만 jQuery는 더 강력하고 어떤 데이터 유형이든 저장할 수 있습니다.jQuery를 사용하여 javascript 배열을 직렬화하지 않고 바로 저장할 수 있습니다.그러나 HTML5 데이터 속성으로 마크업 자체에 있어야 하는 경우 문자열로만 제한됩니다.

기록상으로는 인코딩된 엔티티와 함께 작동하지 않았지만 오브젝트로 파싱하기 위해서는 데이터 속성이 잘 형성된 JSON 오브젝트여야 하는 것 같습니다.

그래서 다음과 같이 객체를 사용할 수 있었습니다.

data-myarray="{&quot;key&quot;: &quot;value&quot;}"

또는 한 개의 인용구를 사용할 수도 있습니다.

data-myobject='{"key1": "value1", "key2": value2}'

즐거운 시간! :D

다음과 같은 노드에 개체를 저장할 수 있습니다.

$('#storageElement').data('my-array', ['a', 'b', 'c']);

var myArray = $('#storageElement').data('my-array');

중첩 배열 또는 다른 방법이 필요한 경우.작동 내용:

$('[data-example]').each(function (i, e) {
    var json = $(e).data('example');
  for(var index in json){
    console.log(json[index]["name"] + "=" + json[index]["value"]);
  }

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div data-example='[{"name": "A", "value": 1}, {"name": "B", "value": 2}]' />
<div data-example='[{"name": "C", "value": 3}, {"name": "D", "value": 4}]' />

율리세 BN이 제시한 바와 같이

아니면 보니파시우스 사룸페트가 지적한 위험한 해결책이지만 작동하는 평가()와 함께.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div data-example="[['A', 1], ['B', 2]]" />
<div data-example="[['C', 3], ['D', 4]]" />

<script>
  $('[data-example]').each(function (i, e) {
    var arrayFromText = eval($(e).data('example'));
    console.log(arrayFromText[0][0] + "=" + arrayFromText[0][1]);
    console.log(arrayFromText[1][0] + "=" + arrayFromText[1][1]);
  });
</script>

PHP를 사용하는 경우 PHP로 다음을 수행합니다.

$arr_test = ['A','C','E'];
$coded = json_encode($arr_test);
// paste coded in data-atribute
print '<div class="funPlus" data-arr_diensten="'. $coded . '"></div>';

검사 시 HTML은 다음과 같습니다.

<div class="funPlus" data-arr_diensten="[&quot;A&quot;,&quot;C&quot;,&quot;E&quot;]"></div>

이제 javascript에서 배열을 검색하지만 값이 하나만 있으면 문자열로 반환됩니다.그래서 이것을 테스트하고 고쳐야 합니다.만약 문자열이라면 우리는 추가 견적을 제거해야 합니다.$(이것은) 개체를 가리켜야 합니다.

var arr_diensten = $(this).data("arr_diensten");
if (typeof arr_diensten == "string") arr_diensten = [arr_diensten.slice(1, -1)];
console.log(arr_diensten);

언급URL : https://stackoverflow.com/questions/16223786/store-and-retrieve-javascript-arrays-into-and-from-html-data-attributes

반응형