Py学习  »  Jquery

jquery click事件自定义属性未定义

Markus • 4 年前 • 685 次点击  

我的页面上有一些按钮。模型看起来像这样

<button type="button" class="js-category-delete" data-id="1">
    Delete
</button>

目标是获得 data-id 属性。目前我正在使用这个javascript。

jQuery('.js-category-delete').on('click', (event) => {
    let id = jQuery(this).attr('data-id');   
});

我的问题是当我将值记录到浏览器控制台时 console.log(id); 我的价值 id 变量是 undefined .

我的代码有什么问题?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/39346
 
685 次点击  
文章 [ 2 ]  |  最新文章 4 年前
Mikhail
Reply   •   1 楼
Mikhail    4 年前

建议你另一种方法:

$('.js-category-delete').on('click', function (event) {
  const clickedItem = jQuery(this); // and also jQuery(event.target)
  const id = clickedItem.data('id');
  console.log(id);
});

这个 function 关键字makes this 一开始你所期望的。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

笔: https://codepen.io/shifu462/pen/WVaGLB


同时,作为

jQuery(event.target).attr('data-id');

我在这里使用了另一个jquery方法来获取数据属性的值。

jQuery(event.target).data('id');

Docs: https://api.jquery.com/data/

gaetanoM
Reply   •   2 楼
gaetanoM    4 年前

使用 arrow function expression 意味着 不是你想要的。 在这种情况下,您需要使用 事件.目标 :

jQuery('.js-category-delete').on('click', (event) => {
        let id = jQuery(event.target).attr('data-id');
        console.log(id);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<button type="button" class="js-category-delete" data-id="1">
    Delete
</button>