gpt4 book ai didi

javascript - 动态生成下拉列表后,来自 Jquery 的 ".on"方法不起作用

转载 作者:行者123 更新时间:2023-11-30 17:45:13 25 4
gpt4 key购买 nike

我对动态生成的选择组合框有疑问。它应该如何工作:

我有一个选择组合框,在我的代码中写入了静态值,下一个应该改变根据上一个选择的结果。下一个,应该以相同的方式工作,但是当在 jquery 中选择一个选项时生成选择组合框,jquery 不再工作,因此不会生成第三个。我对所有这些列表使用相同的类。我该如何解决这个问题?

PS:我使用的是 jquery 1.9.1 版和“.on”方法


$(".select-line-pattern").on("change", function() {
var select_line_pattern_id = $(this).attr("id"); //Returns the id of the select combobox e.g: input-line-add-line-pattern-1
var select_line_pattern_value = $(this).val(); //Returns value of the select combobox e.g: 1
var combobox_line_pattern = $(this).parent("p"); Receive the pattern of the select combobox

var id_split = select_line_pattern_id.split('-'); //Explode by '-' e.g: input-line-add-line-pattern-1
var select_id = id_split.pop(); //Receive the last exploded element e.g: 1
var url_ajax = "search_line_child.php";

$.ajax({
url: url_ajax,
data: { line_pattern: select_line_pattern_value},
dataType: "json",
type: "POST",
success: function(data){

var select_id_next = parseInt(select_id)+1; //Increment the actual id by 1. e.g: 2
var combobox_line_pattern_id = $(combobox_line_pattern).attr("id"); eg: combobox-line-add-line-pattern-1
$("#"+combobox_line_pattern_id+" ~ p" ).remove(); //Remove the next one, if generated
var combobox_line_pattern_new = combobox_line_pattern_id.replace(select_id,select_id_next); eg: combobox-line-add-line-pattern-2
var select_line_pattern_new = select_line_pattern_id.replace(select_id,select_id_next); eg: input-line-add-line-pattern-2
var new_combobox = '<p></p>';
$("#"+combobox_line_pattern_id).after(new_combobox);
var new_select = '';
$('#'+combobox_line_pattern_new).append(new_select);
$(data).each(function(index, element) {
var new_option = ''+element.line_name+'';
$('#'+select_line_pattern_new).append(new_option);
});
}
});

});






<p id="combobox-line-add-line-pattern-1" class="combobox-line-pattern">
<select class="form-control select-line-pattern" name="line_pattern_1" id="input-line-add-line-pattern-1" size="1">
<option value="0">::Without Line::</option>
<option value="1">Line 1</option>
<option value="2">Line 2</option>
<option value="3">Line 3</option>
</select>
</p>

最佳答案

event delegation on() 的语法与您使用的不同,它是

$(static-ancestor-element).on(event, dynamic-selector, handler)

那么试试

$(document).on("change", ".select-line-pattern", function() {
//your stuff
})

您使用的格式与 $(".select-line-pattern").change(handler) 相同,它不处理动态添加的元素

关于javascript - 动态生成下拉列表后,来自 Jquery 的 ".on"方法不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20285385/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com