gpt4 book ai didi

javascript - 当我动态创建元素时,选择的插件不起作用

转载 作者:行者123 更新时间:2023-12-01 05:31:33 26 4
gpt4 key购买 nike

当我动态创建元素时,所选插件不起作用

我从ajax响应动态创建了选择列表,问题是选择的插件无法使用它,请帮我解决它

这是我的代码:

function GetSubCategories(ID) {
$.ajax({
cache: false,
url: '/Home/GetSubCategoriesByAjax',
type: 'GET',
datatype: 'Json',
data: { id: ID },

success: function (data) {
if (data.length > 0) {
console.log(data)


$("#SubListSelect").empty();
var $SubListSelect = $('<select id ="SubListSelect" class = "form-control"></select>');
$SubListSelect.append('<option>Select Sub Category</option>');
$.each(data, function (i, value) {



$SubListSelect.append('<option value=' + value.SubCategoryId + '>' + value.SubCategoryName + '</option>');
});

$("#Div1").empty();
$("#Div1").append($SubListSelect);


}
else {

}
},
error: function (r) {
alert('Error! Please try again.');
console.log(r);

}
});

}

和插件代码:

$(document).ready(function ($) {


$(function () {
$("#SubListSelect").chosen();
});

谢谢

最佳答案

我的建议:

在我的演示中,我为 ajax 使用了不同的 url,并找出了可能的 HTML。

function GetSubCategories(ID) {
$.ajax({
cache: false,
url: "https://api.github.com/users",
type: 'GET',
dataType: "json",
data: { id: ID },
success: function (data) {
if (data.length > 0) {
var SubListSelect = $('<select id ="SubListSelect" class = "form-control"></select>')
.append('<option>Select Sub Category</option>');
$.each(data, function (i, value) {
SubListSelect.append('<option value=' + value.id + '>' + value.login + '</option>');
});
$("#Div1").empty().append(SubListSelect);
$("#Div1").find(SubListSelect).chosen()
} else {
}
},
error: function (r) {
alert('Error! Please try again.');
console.log(r);

}
});
}
$(document).ready(function ($) {
$("#SubListSelect").chosen();
$('#btn').on('click', function(e) {
GetSubCategories('1');
});
});
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>

<!--
The next two lines are the include files for chosen plugin
-->
<link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/chosen/1.1.0/chosen.min.css">
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/chosen/1.1.0/chosen.jquery.min.js"></script>


<div id="Div1">
This is the starting div:
</div>
<button id="btn">Click Me To Create New chosen object into DIV</button>

关于javascript - 当我动态创建元素时,选择的插件不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36983757/

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