最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Best practice to store array of values in html attr? - Stack Overflow

programmeradmin1浏览0评论

What is the best practice to store an array of values in a html (from php) attribute and later access them from javascript/jQuery?

<div class="storage" someAttr=?? /></div>

Its basically a simple array like (code_1,code_2,code_3,...)
Im thinking of doing a simple someAttr="code_1;code_2;code_3" and then exploding it:

      var a = $(this).attr('someAttr');
      (a.split(";")).forEach(function (attr){
        console.log(attr);
      });

What is the best practice to store an array of values in a html (from php) attribute and later access them from javascript/jQuery?

<div class="storage" someAttr=?? /></div>

Its basically a simple array like (code_1,code_2,code_3,...)
Im thinking of doing a simple someAttr="code_1;code_2;code_3" and then exploding it:

      var a = $(this).attr('someAttr');
      (a.split(";")).forEach(function (attr){
        console.log(attr);
      });
Share Improve this question edited Aug 12, 2015 at 13:23 Dainius Vaičiulis asked Aug 12, 2015 at 13:07 Dainius VaičiulisDainius Vaičiulis 5028 silver badges24 bronze badges 3
  • data selectors, E.g: jQuery selectors on custom data attributes using HTML5 – Alex K. Commented Aug 12, 2015 at 13:11
  • 2 You could try formatting it to JSON from PHP, then have JavaScript parse it. – user3117575 Commented Aug 12, 2015 at 13:15
  • I would like to go with data-attributes introduced in HTML5. – Mritunjay Commented Aug 12, 2015 at 13:19
Add a ment  | 

2 Answers 2

Reset to default 6

You can json_encode your array on the PHP side, add it in as a data-attribute on the HTML side, and then parse it out on the JavaScript side.

<!DOCTYPE html>
<html>

  <head>
    <script src="http://code.jquery./jquery-1.11.3.min.js"></script>
    <script>
      $(document).ready(function() {
        var jsArr = JSON.parse($('#phpArr').attr('data-attr'));
      });
    </script>
  </head>

  <body>
    <span id="phpArr" data-attr='<?php echo json_encode(arr); ?>'></span>
  </body>

</html>

You can store like this in html attribute then you can split that into array using JavaScript with help of Substring functions

<li  id="P01[01]"></li>
发布评论

评论列表(0)

  1. 暂无评论