为什么我不能访问CoffeeScript中的动态内容选择器

Why can I not access a selector of dynamic content in CoffeeScript?

本文关键字:动态 选择器 不能 访问 CoffeeScript 为什么      更新时间:2023-09-26

我正在向页面添加动态内容,以将表单控件的数量限制在用户需要的范围内。我使用以下代码从下拉列表中获取用户所做选择的信息,然后更改另一个限制他们可以搜索的信息的控件。例如,我不允许某人执行类似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')返回"undefined"。我认为这是因为内容以前不存在,所以代码在动态添加后找不到它。尽管我预计将监听器添加到$('body')中会解决这个问题。有人能给我指正确的方向吗?谢谢

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