在向选择框动态添加选项后,触发器不起作用

时间:2014-06-30 17:15:36

标签: javascript jquery

我选择了标识为test的框。我触发它就像:

$("#test").on('change', function() { alert('test'); })

这是第一次有效,但在我添加一些选项以动态选择框之后:

var option = $("<option>")
          .attr('value', this.value)
          .attr('class', this.class)
          .html(this.text);

        // if id corresponds to selected id then select it
        if (parseInt(this.value) == selected_id) {
          option.attr('selected', 'selected');
        }

        // append to select
        $("#test").append(option);

触发器不起作用。怎么办?

2 个答案:

答案 0 :(得分:0)

这应该这样做:

$(document).on('change', '#test', function() { alert('test'); });

以下内容:

    var trigger = false;
    if (parseInt(this.value) == selected_id) {
      option.attr('selected', 'selected');
      trigger = true;
    }

    // append to select
    $("#test").append(option);
    !trigger || $('#test').change();

注意:只需在新选项中添加selected属性,select元素就不会触发。您必须在适用时使用.change().trigger('change')明确触发它。当用户手动选择值时,value都已设置,同时触发change事件(如果新值不等于之前的值)。

答案 1 :(得分:0)

试试这个:

var option =“<option value='"+this.value+"' class='"+this.class+"'>"+this.text+"</option>”; $("#test").append(option);

而不是:

var option = $("<option>")
          .attr('value', this.value)
          .attr('class', this.class)
          .html(this.text);

然后追加它。

你可以发布整个脚本吗?或者至少是一个更完整的例子?