jquery - 使用 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
解决方案
$(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()
已经进行了解析。
推荐阅读
- java - JavaFX 图像 getUrl() 在 Excelsior jet 中导致 NoSuchMethodError
- c# - 绑定用户控件 WPF
- sql - 在 Oracle 11g 中选择两个值之间的行
- python - 在理解代码方面需要帮助
- android - 如何每隔一定时间安排一个任务
- html - Building a responsive "centered icons with descriptions" layout
- java - 尝试从 Fragment 切换到 Activity 时出现 TransactionTooLargeException
- javascript - 无法让“Fitty”与 Angular 2+ 一起使用
- mongodb - 如何将增量 mongodb 数据库迁移到生产环境?
- html - 如果包含的元素是自动调整大小的,垂直线 div 会消失