我目前有一个像这样的 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("[数据成本]"));仅返回值。 我试过这个:
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/