gpt4 book ai didi

jquery - 可以在 CoffeeScript 中循环每个吗?

转载 作者:行者123 更新时间:2023-12-03 22:00:36 24 4
gpt4 key购买 nike

我正在尝试以编程方式创建一些 JavaScript 按钮来切换页面上的可见性(用于快速标签过滤)。这适用于一个标签:

trigger = ".sales-focus-btn"
target = ".sales-focus"

jQuery ->
$(trigger).toggle ->
$("#primary-content").find('.container').hide()
$("#primary-content").find(target).show()
, ->
$("#primary-content").find('.container').show()

是否可以在coffeescript中做类似的事情,但使用数组,例如

trigger = [
".sales-focus-btn"
".service-focus-btn"
".other-focus-btn"
...
]
target = [
...
]

是否可以循环并为每种类型的标签创建切换?

更新

是的,这是可能的。使用表格:

myFunction = (el) -> console.log el
myFunction elem for elem in array

最佳答案

当然有可能:

content = $('#primary-content')
container = content.find('.container')

tags = [
'.sales-focus'
'.service-focus'
'.other-focus'
]

$.each tags, (tag) ->
target = content.find(tag)
$(tag + "-btn").toggle ->
container.hide()
target.show()
, ->
container.show()

记住缓存您的 DOM 元素。或者使用 for tag in Tags 而不是 jQuery.each 标签,(tag) -> ...:

for tag in tags
do ->
target = content.find(tag)
$(tag + "-btn").toggle ->
container.hide()
target.show()
, ->
container.show()

(正如 @epidemian 指出的那样,do -> IIFE 对于将每个目标 保持在范围内是必要的)

关于jquery - 可以在 CoffeeScript 中循环每个吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11371458/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com