我可以让数据结构显示为 HTML 元素吗?



我所说的数据结构是指哈希或对象。这里有一个例子(用咖啡脚本写的,但我相信你能理解):

left_arrow = { clickable : true }
$('.left_arrow').click ->
    console.log self.clickable /* want this to log 'true'

该 HTML:

<div class = "left_arrow"> < </div>

从概念上讲,这可以被视为将元素的类/ID与javascript对象映射。

你可以遍历你想要保存的属性,并且由于看起来你已经在使用 jQuery,所以使用 jQuery 的数据方法将它们保存到元素中。

attributes = {
  left_arrow: { clickable : true }
}
for attribute_name, attribute_data in attributes
  ($ ".#{attribute_name}").data attribute_data
# ...
($ '.left_arrow').click ->
  console.log ($ this).data('clickable') # logs true

最新更新