简体   繁体   English

从html数据属性循环并显示javascript数组内容

[英]Looping and displaying javascript array content, from html data attribute

I have an array which is being passed though html data element 我有一个通过html数据元素传递的数组

  <button type="button" class="open-my-modal btn btn-primary" 
data-number="'.htmlspecialchars(json_encode($myArray), ENT_QUOTES, 'UTF-8')

The Array holds a set of different arrays which have a format like this 数组包含一组不同的数组,它们的格式如下

Array(
  [0] => ABC
  [1] => DEF
  [2] => GHI
  [3] => JKL
 )
Array(
 [0] => MNO
 [1] => 123A
 [2] => 123B
 [3] => 123C
)
Array(
[0] => orange
[1] => yellow
[2] => green
[3] => blue
)

The data is being passed to a modal like the field id is shown below 数据正在传递给模态,如下所示。

<tr>
    <td><span id ="exampleone"></span></td>
    <td><span id ="exampletwo"></span></td>
    <td><span id ="examplethree"></span></td>
    <td><span id ="examplefour"></span></td>
</tr>

and a script which links the id's and the data 和链接ID和数据的脚本

<script>

$(document).ready(function () {             
$(".open-my-modal").click(function(){
  $("#exampleone").html($(this).data("number")[0]);

This displays ABC,DEF,GHI,JKL all on the screen correctly. 这将在屏幕上正确显示ABC,DEF,GHI,JKL。 But i want to dynamically do this. 但我想动态地做到这一点。 For example 例如

<td><span id ="exampleone"></span></td> <!-- output will be ABC-->
<td><span id ="exampleone"></span></td><!-- output will be DEF-->
etc, etc

I am pulling my data dynamically so each array may have more than 4 entries it will vary from time to time. 我动态地提取数据,所以每个数组可能有4个以上的条目,并且会不时变化。

I am stuck on where i need to get the length of numbers(data) and how to generate and id for it dynamically 我被困在需要获取数字(数据)长度以及如何动态生成和标识的位置上

(<td><span id ="dynamically generated">) 

and then how to dynamically link the id with the correct 然后如何将ID与正确的动态链接

data($("#number").html($(this).data("number"));)

To generate the items in your list dynamically you can use the following code 要动态生成列表中的项目,可以使用以下代码

HTML (replace your code) HTML (替换您的代码)

<tr id="parentNode"></tr>

JavaScript (put inside your jQuery code) JavaScript (放入jQuery代码中)

$.each($(this).data('number'), function(index, value){ $("#parent").append($('<td>').append($('<span>', {'id' : 'example' + index , 'text' : value}))); });

This will generate <td><span id=example1>value1</span></td> and so on. 这将生成<td><span id=example1>value1</span></td> ,依此类推。

I strongly suggest you to use AJAX to get the data from your server. 我强烈建议您使用AJAX从服务器中获取数据。 Here is a guide 这是一个指南

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM