点击按钮获取data- *值

时间:2016-07-10 14:29:06

标签: jquery

我有这个按钮

<button type="button" class="breakbtn btn btn-danger btn-cons btn-primary btn-block m-t-5" data-amounts="'+amounts+'" id="'+ti+'">Break</button>

我点击按钮后得到id和data-amount字段的值。

我可以使用此代码获取id

var arr = event.target.id;

但这不会给出值

var initial = event.target.attributes.getNamedItem('data-amounts');

这是一个小提琴https://jsfiddle.net/8oLrxort/1/

2 个答案:

答案 0 :(得分:1)

使用dataset property to get data-* attribute

var initial = event.target.dataset.amounts;

$("button").click(function() {
  var arr = event.target.id;
  var id = arr;
  var initial = event.target.dataset.amounts;
  alert(arr);
  alert(initial);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="breakbtn btn btn-danger btn-cons btn-primary btn-block m-t-5" data-amounts="200" id="10">Break</button>

答案 1 :(得分:1)

您有两种选择:

var initial = event.target.getAttribute('data-amounts');

或者:

var initial = event.target.dataset.amounts;

function withDataset(e) {
  console.log(e.target.dataset.amounts)
}

function withGetAttribute(e) {
  console.log(e.target.getAttribute('data-amounts'));
}

var one = document.getElementById('one'),
  two = document.getElementById('two');

one.addEventListener('click', withDataset);
two.addEventListener('click', withGetAttribute);
<button id="one" data-amounts="20">button 1</button>
<button id="two" data-amounts="400">button 2</button>

JS Fiddle demo

参考: