首页 > 解决方案 > 使用 Jquery 获取数据属性值

问题描述

我目前有一个这样的 li:

<li value="100" data-cost="137.00"><span>100</span></li>

我正在尝试访问数据属性成本值。
在此示例中,我希望获得 137.00 的回报

我正在做一个控制台日志,因为我认为这会起作用:

console.log($(this).closest("[data-cost]"));

我的返回显示了整个对象,我可以在那里看到数据集: 在此处输入图像描述

我使用最接近的原因是因为我目前需要在单击它时选择这个 li,所以我使用 span 来选择它。

这是选择元素的整个代码块。

  $(function(){
    jQuery(".po-list li span").on("click", function(){
      var span = $(this).clone();
      var options_col = $(this).closest('.options-col');
      console.log($(this).closest("[data-cost]"));
      span.attr('class','cur-option-val');
      options_col.find('.cur-option-w .cur-option-val').replaceWith(span);
    });
  });

正如我上面所说,我期待这个:console.log($(this).closest("[data-cost]")); 只返回值。我试过这个:

console.log($(this).closest("[data-cost]").val());
console.log($(this).closest("[data-cost]").text());

Both of those returned the value of the span not of the data-cost

标签: jquery

解决方案


$(this).closest("[data-cost]")只会返回具有data-cost- 您可以看到的属性的元素。使用.data()方法提取值:

$(this).closest("[data-cost]").data("cost");

这将返回属性中内容的字符串表示形式。如果您需要它作为数字 - 将其转换为:

//Ignore this, casting wasn't needed as pointed out in comments
//let dataCost = +$(this).closest("[data-cost]").data("cost"); //the "+" will cast the string to a number

编辑:正如 Barmar 指出的那样,.data()已经进行了解析。


推荐阅读