как получить data-vale1, data-value2, data-value3 из кнопки - PullRequest
0 голосов
/ 06 февраля 2020

как получить 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

1 Ответ

0 голосов
/ 06 февраля 2020

Чтобы получить атрибуты данных через .data, атрибут данных должен быть в кебаб-кейсе, например, 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>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...