【问题标题】:Remove substring in jQuery删除 jQuery 中的子字符串
【发布时间】:2012-03-17 07:16:29
【问题描述】:

我正在使用 jQueryUI 组合框。如果用户在select 元素中输入不是option 的字符串,它会创建一个具有该值的新option 元素。问题是它当前在输入的值前面加上“未定义”。如何在提交之前删除“未定义”子字符串?代码如下:

change: function(event, ui) {
    if (!ui.item) {
        var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex($(this).val()) + "$", "i"),
            valid = false;
        select.children("option").each(function() {
            if ($(this).text().match(matcher)) {
                this.selected = valid = true;
                return false;
            }
        });
        if (!valid) {
            new_value = self.options.precede_new_with + $(this).val();
            option = $('<option value="' + new_value + '">' + $(this).val() + '</option>');
            select.append(option);
            select.val(new_value);
            return false;
        }
    }
}​

【问题讨论】:

    标签: jquery autocomplete combobox substring


    【解决方案1】:

    看来问题在于 self.options.precede_new_with 正在返回“未定义”。

    【讨论】:

      【解决方案2】:

      你是说这条线?

      new_value = self.options.precede_new_with + $(this).val();
      

      创建组合框实例时,将此选项设置为空字符串:

      $( "#combobox" ).combobox({
          precede_new_with: ''
      });
      

      或者在这种情况下通过返回一个空字符串来更改实现以检查可能的未定义:

      new_value = (self.options.precede_new_with || '' ) + $(this).val();
      

      【讨论】:

        【解决方案3】:

        在附加 option 时,您可以检查它是否未定义,然后在其前面加上空字符串。这样您在提交表单时无需进行任何处理。

        试试这个。

        if ( !valid ) {
        
           new_value = (self.options.precede_new_with || '') + $(this).val();
                   //this will prepend empty string if undefined
        
           option = $('<option value="' + new_value + '">' + $(this).val() + '</option>');
           select.append(option);
           select.val(new_value);
           return false;
        }
        

        【讨论】:

        • @Dowvoter - 请留下原因,以便我解决问题,让其他人可以使用答案?
        【解决方案4】:

        感谢您的建议,抱歉,我花了一点时间才回来,我一直很忙。无论如何,我最终只需要将new_value 设置为等于$(this).val() 并摆脱self.options.precede_new_with

        【讨论】:

          猜你喜欢
          • 2013-04-07
          • 1970-01-01
          • 2015-11-20
          • 2018-05-30
          • 2011-02-26
          • 2019-09-08
          • 1970-01-01
          相关资源
          最近更新 更多