【问题标题】:Issues with getting object vars through a string通过字符串获取对象变量的问题
【发布时间】:2018-08-07 22:06:01
【问题描述】:

不确定标题是否有意义,但我想通过点击事件发送数据,此点击事件将从预设的 var(在本例中为 product101)获取数据,因为此 var 以 JSON 格式格式化,我无法似乎检索数据,它总是返回一个未定义的。由于 var 是一个对象,但是当我使用数据集时,var 是一个字符串,对吗?

 // inside a loop
 <div class="container">

     <script> var product<?=$id?> = {"category":"cars"}</script>

     <div data-my-product="product<?=$id?>">
         //all the product stuff
     </div>

 </div>

 //located in the footer
 $('[data-my-product]').click(function(){

      //demo
      var pro = $(this).data('my-product');
      alert(pro.category);//returns undefined

 })

当我点击产品时,它会返回一条“未定义”的警报消息。

请注意,产品是在循环中生成的。

【问题讨论】:

  • 您的数据属性仅包含字符串“product101”。为了从 .data() 获取该对象,您必须将 JSON 文本直接放入属性值中。
  • 是的,我很遗憾地知道,由于围绕此设置的几个事件,它需要单独设置 var/obj。
  • $(this).data('my-product') === "product101"。不等于"product101",等于"product101"
  • 属性或数据,同样的问题
  • @deepakthomas no .data() 是正确的。 OP 你不能做你的代码试图做的事情。 HTML 解析器不知道 JavaScript 上下文。

标签: javascript jquery


【解决方案1】:

概述

您最好的办法是创建一个对象或Map,其中包含您要以这种方式查找的内容,然后将它们作为属性或条目放在上面。

有一个对象:

var items = {
    product101: {category: "cars"}
};

或者,如果您想对对象上存在的默认继承属性持怀疑态度,您可能会使用没有原型的对象:

var items = Object.create(null);
items.product101 = {category: "cars"};

然后在您的点击处理程序中:

alert(items[pro].category);

现场示例:

$('[data-my-product]').click(function() {
  var pro = $(this).data('my-product');
  alert(items[pro].category);
});
<div class="container">

  <script>
    var items = {
        product101: {category: "cars"}
    };
  </script>

  <div data-my-product="product101">
    //all the product stuff
  </div>

</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Map:

var items = new Map([
    ["product101", {category: "cars"}]
]);

然后在您的点击处理程序中:

alert(items.get(pro).category);

现场示例:

$('[data-my-product]').click(function() {
  var pro = $(this).data('my-product');
  alert(items.get(pro).category);
});
<div class="container">

  <script>
    var items = new Map([
        ["product101", {category: "cars"}]
    ]);
  </script>

  <div data-my-product="product101">
    //all the product stuff
  </div>

</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

旁注:虽然您可以使用data 访问data-* 属性的值(间接),但这样做会为元素设置数据缓存并使用属性值初始化该缓存。如果您只是想获取字符串,.attr("data-my-product") 更直接。详情请见this answer

【讨论】:

  • 谢谢,但不知道如何在点击事件中使用它
  • @user759235 - 您确实使用“然后在您的点击处理程序中”行来代替问题代码中的alert。我添加了实时示例。
  • @user759235 - 是的,他们有。查看实时示例。
  • 好吧,奇怪,当我单击“运行代码 sn-p”按钮时,我看到一条错误消息
  • 在这两种情况下(Chrome OSX)我都会看到一个弹出窗口说“汽车”
猜你喜欢
  • 2012-01-29
  • 1970-01-01
  • 2012-05-02
  • 2020-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多