【问题标题】:Can't read data- attribute with Jquery无法使用 Jquery 读取数据属性
【发布时间】:2019-06-08 20:13:48
【问题描述】:

我正在循环中使用 PHP 生成 Bootstrap 分页元素。

<button class="page-link" data-page="'.$page_number.'">'.$page_number.'</button>

元素生成正确:

<button class="page-link" data-page="1">1</button>

然后在我的脚本中,我需要让这个数据页向前传递。

我正在尝试这样做:

$('#taskcontainer').on("click", $(".page-link"), () => {
       console.log($(this).data("page"));  
    })

但是点击那些按钮只会给我

undefined

我正在绑定到#taskcontainer,因为这个分页元素是由 PHP 生成的。

【问题讨论】:

  • 把jQuery改成$('#taskcontainer').on("click", ".page-link", () =&gt; { console.log($(this).data("page")); })
  • @Dharman - 如果你不使用this,this 更直接的等价物是event.currentTarget 而不是event.target。

标签: jquery


【解决方案1】:

有两个问题:

  1. 您的委托处理程序代码不正确,您想传递 选择器,而不是 jQuery 对象,作为第二个参数。 (见the documentation。)

  2. 您正在使用箭头函数。要让 jQuery 设置 this,您需要一个传统函数(更多内容请参见 this answer)。

所以:

$('#taskcontainer').on("click", ".page-link", function() {
// No $( and ) here ------------^^^^^^^^^^^^  ^^^^^^^^^^--- no arrow function here
   console.log($(this).data("page"));  
})

如果你想继续使用箭头函数,你不能使用this,但你可以接受事件参数并使用它的currentTarget属性:

$('#taskcontainer').on("click", ".page-link", (event) => {
// No $( and ) here ------------^^^^^^^^^^^^  ^^^^^^^--- event parameter
   console.log($(event.currentTarget).data("page"));
// --------------^^^^^^^^^^^^^^^^^^^
})

另请参阅 this answer 关于 data 与 attr 的对比。

【讨论】:

    猜你喜欢
    • 2013-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-01
    • 1970-01-01
    • 2018-02-12
    • 2018-06-18
    • 1970-01-01
    相关资源
    最近更新 更多