我选择了标识为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);
触发器不起作用。怎么办?
答案 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);
然后追加它。
你可以发布整个脚本吗?或者至少是一个更完整的例子?