首页 > 解决方案 > 如何从按钮获取 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

标签: javascriptjquery

解决方案


要通过 检索数据属性.data,数据属性应为 kebab-case,例如data-foo-bar,而不是camelCase然后您可以通过将camelCased 字符串传递到.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>


推荐阅读