使用jQuery获取数据属性值

时间:2018-08-23 18:30:08

标签: jquery

我目前有一个这样的人:

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

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

我正在做一个控制台日志,因为我认为这可以工作:

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

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

我使用最接近的原因是因为当前单击该li时需要选择它,所以我使用跨度来选择它。

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

  $(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

1 个答案:

答案 0 :(得分:2)

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

相关问题