javascript - 如何从按钮获取 data-vale1、data-value2、data-value3
问题描述
如何从按钮获取 data-vale1、data-value2、data-value3
$('.update').on('click', function() {
var obj = $(this).data();
var empId = $(this).data('logDate');
var indexId = $(this).data("index");
var logDate = $(this).data("logDate");
console.log(obj);
console.log(indexId);
console.log(empId);
console.log(logDate);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="update" data-empId="123" data-indexId="234" data-logDate='2020-01-01'>click </button>
这是结果
{logdate: "2020-01-01", indexid: 234, empid: 123}
undefined
undefined
undefined
解决方案
要通过 检索数据属性.data
,数据属性应为 kebab-case,例如data-foo-bar
,而不是。camelCase
然后您可以通过将camelCase
d 字符串传递到.data
:
$('.update').on('click', function() {
var obj = $(this).data();
var empId = $(this).data('empId');
var indexId = $(this).data("indexId");
var logDate = $(this).data("logDate");
// console.log(obj.indexId);
console.log(indexId);
console.log(empId);
console.log(logDate);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="update" data-emp-id="123" data-index-id="234" data-log-date='2020-01-01'>click </button>
这是最好的方法,但如果你不能改变 HTML,你也可以使用attr
:
$('.update').on('click', function() {
var obj = $(this).data();
var empId = $(this).attr('data-empId');
var indexId = $(this).attr('data-indexId');
var logDate = $(this).attr('data-logDate');
// console.log(obj.indexId);
console.log(indexId);
console.log(empId);
console.log(logDate);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="update" data-empId="123" data-indexId="234" data-logDate='2020-01-01'>click </button>
或者,从 中.data()
提取属性,但它们会丢失它们的大小写:
$('.update').on('click', function() {
var obj = $(this).data();
var empId = obj.empid;
var indexId = obj.indexid;
var logDate = obj.logdate
// console.log(obj.indexId);
console.log(indexId);
console.log(empId);
console.log(logDate);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="update" data-empId="123" data-indexId="234" data-logDate='2020-01-01'>click </button>
推荐阅读
- c - 数组如何绕过其声明的长度
- android - 如何修复 Epson Android SDK 中的“未找到实现方法名称”?
- docker - kubernetes deployment notification to slack channel using webhook
- r - 合并包含具有相同结构的列表的列表
- html - 如何在整个正文中添加自定义文本选择
- java - 在另一个 java 项目中创建一个 maven 项目
- android - 有没有什么特殊的方式来实现 admob 广告?
- google-cloud-platform - 阻止 traefik 入口回复 IP 请求
- android - 使用带有实时数据和不使用实时数据的视图模型之间的区别
- asp.net-core - 将我的依赖注入到 CustomQueryCompiler