$(this).data('dynamic_id') 未定义,除非在警报中
$(this).data('dynamic_id') is undefined except in alert
如何使用数据属性将动态生成的 ID 从 rails 应用程序传递到 jQuery?当我尝试时,值 returns 未定义,除非我将它发送到警告框。
此代码(使用调试 link 作为 hack):
$(document).on "page:change", ->
$('.debug_link_id').click ->
alert $(this).data('dynamic_id)
在警告框中显示 dynamic_id。
但是,使用相同的选择器,此代码:
$(document).on "page:change", ->
jqVar = $(this).data('dynamic_id')
$('.debug_link_id').click ->
alert jqVar
在警告框中显示 "undefined"。
[使用 .attr('data-dynamic_id') 给出相同的结果]
请告诉我:
- 为什么第一个代码有效而第二个无效
- 如果有更好的策略将动态 ID 拉入 jQuery
尝试使用 event delegation 在处理程序中将 this
设置为 "#debug_link_id"
。
$(document).on "page:change", "#debug_link_id", ->
那是因为你在错误的地方提到了 this
..
$(document).on "page:change", ->
$('#debug_link_id').click ->
alert $(this).data('dynamic_id)// <-- That "this" is referring a object with id debug_link_id
$(document).on "page:change", ->
jqVar = $(this).data('dynamic_id') //<-- That "this" is referring a object that I don't know where this is come from...
$('#link_id').click ->
alert jqVar
如何使用数据属性将动态生成的 ID 从 rails 应用程序传递到 jQuery?当我尝试时,值 returns 未定义,除非我将它发送到警告框。
此代码(使用调试 link 作为 hack):
$(document).on "page:change", ->
$('.debug_link_id').click ->
alert $(this).data('dynamic_id)
在警告框中显示 dynamic_id。
但是,使用相同的选择器,此代码:
$(document).on "page:change", ->
jqVar = $(this).data('dynamic_id')
$('.debug_link_id').click ->
alert jqVar
在警告框中显示 "undefined"。 [使用 .attr('data-dynamic_id') 给出相同的结果]
请告诉我:
- 为什么第一个代码有效而第二个无效
- 如果有更好的策略将动态 ID 拉入 jQuery
尝试使用 event delegation 在处理程序中将 this
设置为 "#debug_link_id"
。
$(document).on "page:change", "#debug_link_id", ->
那是因为你在错误的地方提到了 this
..
$(document).on "page:change", ->
$('#debug_link_id').click ->
alert $(this).data('dynamic_id)// <-- That "this" is referring a object with id debug_link_id
$(document).on "page:change", ->
jqVar = $(this).data('dynamic_id') //<-- That "this" is referring a object that I don't know where this is come from...
$('#link_id').click ->
alert jqVar