【问题标题】:Knockout.js loop through divs on page and generate button. coffeescriptKnockout.js 循环遍历页面上的 div 并生成按钮。咖啡脚本
【发布时间】:2015-03-24 04:07:44
【问题描述】:

我正在尝试遍历页面上的所有 div,并找到所有具有相同类的 div:item 并将它们变成一个按钮。

这里是html中的数据示例:

         <div class='item'>
          <span><a class='test' href='http://google.com'>tester1</a></span>
          </div>
          <div class='item'>
          <span><a class='test' href='http://google.com'>tester2</a></span>
          </div>
          <div class='item'>
          <span><a class='test' href='http://google.com'>tester</a></span>
          </div>
          <div class='item'>
          <span><a class='test' href='http://google.com'>test</a></span>
          </div>

问题是可能存在数百个这样的 div,这就是我想使用 ko 的原因。

我的咖啡脚本:

define ["knockout", "text!./test-page.html"], (ko, template) ->
VM = () =>
    window.xxx = @


return {
    viewModel: VM
    template: template
}

我不确定如何继续,有什么提示可以让我朝着正确的方向前进吗?

【问题讨论】:

  • 你不使用RequireJS吗?这个问题也应该被标记。从未使用过 Coffeescript,但是当我将您的 Cs 与常规 JS here 进行比较时,您应该首先修复缩进,这对 Cs 来说似乎至关重要,然后阅读 Knockout and AMD modulesthis Stackoverflow question 并且可能还会学习 OO JS 概念。跨度>
  • 是否有理由不能使用 jQuery 选择器,然后为每个返回的元素将其转换为按钮?例如$(".item").each(function(){...turn to button...})
  • 数据从何而来?是硬编码的吗?
  • 如果你想为此使用敲除,你很可能不会通过 DOM 搜索来查找 div。如果你想为此使用敲除,你可能会首先让敲除创建 div 并有一个 bindingHandler 使它成为一个按钮(但是,为什么不把它也变成一个实际的 HTML 按钮,而你在它呢? )。您询问的方式(通过 DOM 搜索)更像是一种 jQuery 方式,而不是淘汰方式。对于 jQuery,请看上面@Jarga 的评论。

标签: javascript html knockout.js coffeescript


【解决方案1】:

我不确定您是否有足够的资源使用 Knockout 来执行此操作。也许把小提琴放在一起?

但是,您可以使用 jQuery 来实现这一点,然后让 Knockout 知道如果需要,事情已经发生了变化。

$('.item').each ->
 if $(this).hasClass 'buttonClass'
  // turn $(this) into a button and manipulate in other ways
 else
 // ad a class or something that lets you find these in the future perhaps?

【讨论】:

    猜你喜欢
    • 2012-04-10
    • 2015-03-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-18
    • 1970-01-01
    • 1970-01-01
    • 2012-06-14
    • 1970-01-01
    相关资源
    最近更新 更多