【问题标题】:Why can I not access a selector of dynamic content in CoffeeScript?为什么我无法访问 CoffeeScript 中的动态内容选择器?
【发布时间】:2016-03-29 22:49:42
【问题描述】:

我正在向我的页面添加动态内容,以将表单控件的数量限制在用户需要的范围内。我使用以下代码从下拉列表中获取有关用户所做选择的信息,然后我更改了另一个限制他们可以搜索的信息的控件。因此,例如,我没有允许某人执行 first_name = 47 之类的搜索,而是将表单控件更改为仅接受某些字符的文本框 - 将它们限制为 first_name = Steve 之类的内容。

  $('body').on 'change', 'select[name$="[name]"]', ->

    # This block is simply figuring out which element was changed and locating it's corresponding form control where the user inputs information.
    name_string = $(this).attr 'id'
    selected_value = $("option:selected", this).text().toLowerCase()
    value_id = $(this).attr('id').replace('name', 'value')
    value_id = value_id.replace('a','v')

    # This block is executed if the attribute the user wishes to search on should only be true/false
    if attributes_for_true_false_select.indexOf(selected_value) > -1

      # Create a true/false drop down list with the correct `name` and `id` attributes
      true_false_drop_down_list = '<select class="form-control" name="' + $('input[id=\''+value_id+'\']').attr('name') +
        '" id="' + $('input[id=\''+value_id+'\']').attr('id') + '"><option value="1">True</option><option value="0">False</option></select>'

      # Replace the current form selector with the new true/false drop down list
      $('#'+value_id).replaceWith(true_false_drop_down_list)

    else if ...

现在上面的代码可以正常工作,但只是第一次。在我更改了一次表单控件后,再试一次,代码为$('input[id=\''+value_id+'\']').attr('name')$('input[id=\''+value_id+'\']').attr('id') 返回“未定义”。我认为这是因为内容之前不存在,因此在动态添加后代码找不到它。虽然我希望将监听器添加到 $('body') 会解决这个问题。谁能指出我正确的方向?谢谢!

【问题讨论】:

  • 你的新元素匹配select[name$="[name]"]选择器???
  • 以为我已经弄明白了,但我的值控制字符串末尾缺少[value]——但事实证明并非如此。是的,[name] 选择器仍然匹配我所知道的。该元素永远不会只更改相应的 [value] 形式。
  • 你为什么不使用字符串插值($("input[id='#{value_id}']"))而不是所有的转义和+ing?读起来好一点。
  • @muistooshort 谢谢不知道

标签: javascript jquery html coffeescript


【解决方案1】:

问题出在我构建要插入的新表单控件的部分。$('input[id=\''+value_id+'\']').attr('id') -- 我只需要删除其中的input 部分,然后通过 id 属性简单地查找。这是因为我添加的某些表单控件不是input,例如显示的select

【讨论】:

    猜你喜欢
    • 2014-04-24
    • 2020-11-03
    • 1970-01-01
    • 2016-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多