【问题标题】:Passing Javascript Data attribute array value传递 Javascript 数据属性数组值
【发布时间】:2017-07-13 02:16:23
【问题描述】:

我有一个像 $myArray 这样的 php 数组

Array ( 
     [0] => Array ( 
            [Fruit] => Apple 
            [Number] =>
               Array (
                 [0] => 1
                 [1] => 2
                 [2] => 3
               )

            [supplier] =>
              Array ( 
                [0] => Store 1 
                [1] => Store 2 
                [2] => Store 3 
              )
            [description] => 
              Array (
                [0] => SAmple text for apple
                [1] => Sample text for apple 2
                [2] => Sample text for apple 3
             )
     [1] => Array ( 
            [Fruit] => Orange 
            [Number] =>
               Array (
                 [0] => 7
                 [1] => 8
                 [2] => 9
               )

            [supplier] =>
              Array ( 
                [0] => Store 4 
                [1] => Store 5 
                [2] => Store 6 
              )
            [description] => 
              Array (
                [0] => SAmple text for orange
                [1] => Sample text for orange 2
                [2] => Sample text for orange 3
             ))

我使用for循环和javascript数据属性从这个数组传递值,按下按钮打开一个模式。

I am looping though all the entries in my array like this 

for($index=0; $index < count($myArray); $index++){

 <!--some code here -->

 <button type="button" class="open-modal btn btn-primary" data-first-fruit="'.$myArray[$index]["description"][0]

这会将苹果存储为“第一描述”

在我的 javascript 函数中打开模式,我将该数据传递给我在代码中创建的 div。

$("#descriptiondiv").html($(this).data("first-description"));

这可以正常工作并正确显示苹果。

但我将处理大量数据并保存如下值

data-first-description="'.$myArray[$index]["description"][0]
data-second-description="'.$myArray[$index]["description"][1]
data-third-description="'.$myArray[$index]["description"][2]

不会很理想

每次我传递如下数据时

 data-first-description="'.$myArray[$index]["description"]

我得到一个数组到字符串的转换错误。

有没有办法可以将整个 ["description"] 数据传递给 data 属性?

【问题讨论】:

  • 当您使用 jQuery 时,您可以使用 data(),它不会创建属性,也不会转换为字符串,而是将数据直接存储在元素对象上。
  • 你这里有多个数组,所以你需要在你的声明前面多一个索引$myArray[0][$index]["Fruit"]

标签: javascript php jquery arrays


【解决方案1】:

这似乎是 php(尽管问题未标记为 php)。

如果是这样,您可以 json_encode() 将数组传递给数据属性,jQuery data() 会将其读取为 javascript 数组。

使用单引号包裹输出以避免html中的不匹配

data-fruit=\''. json_encode($array) . '\''

【讨论】:

  • 我需要改变$myArray的结构吗?
  • 还不能真正回答这个问题......我对你想如何使用它以及为什么有一个外部数组有点困惑。试试这个console.log($('[data-fruit']:first').data('fruit')),你可以在浏览器开发工具控制台中看到你正在使用的东西
  • data-first-fruit="'.$myArray[$index]["Fruit"][0] 按原样工作,我得到苹果,这是正确的。我希望能够得到去掉最后的 [0] 并传递所有水果的值。
  • 对......它是一个数组......所以这就是你的json_encode
  • 使用 data-fruit= "'.json_encode($myArray[$index]["Fruit"]).'" 我得到空值
猜你喜欢
  • 2016-11-13
  • 2020-01-21
  • 2012-01-31
  • 2015-08-03
  • 1970-01-01
  • 2023-03-24
  • 1970-01-01
  • 1970-01-01
  • 2012-08-12
相关资源
最近更新 更多