jquery - 使用Jquery获取数据属性值

标签 jquery

我目前有一个像这样的 li:

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

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

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

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

我的返回显示了整个对象,我可以在那里看到数据集: enter image description here

我使用最接近的原因是因为我当前需要在单击此 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("[数据成本]"));仅返回值。 我试过这个:

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

最佳答案

$(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() 已经进行了解析。

关于jquery - 使用Jquery获取数据属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51992167/

相关文章:

javascript - Ajax 事件仅工作一次

boolean-logic - 不清楚这个 jQuery 语法 : return ! $()

php - 将悬停时的边框颜色设置为数据库中的动态颜色

javascript - AjaxSetup 与 jqgrid 冲突

javascript - 将数组从 Html 合并到 Jquery

jQuery 追加问题

jquery - 防止 HTML5 contenteditable 字段中 'return' 键的默认行为

javascript - 网页如何防止粘贴事件?

javascript - 是否可以仅通过 CSS 更改页面加载时特定元素的背景?

javascript - 在 html css 中锁定表单后更改边框