gpt4 book ai didi

javascript - 如何从添加到 html 页面的动态元素中获取数据?

转载 作者:行者123 更新时间:2023-11-27 22:57:47 25 4
gpt4 key购买 nike

在下面我写了我的 html 页面的一部分。

<form method="post" enctype="multipart/form-data">
<div>
<label>Brand Name:</label>
<input type="text" asp-for="@Model.Name">
</div>
<div id="divCategory">

</div>
<button type="button" id="btnAddCategory">Add Category</button>
<button>Create new Brand</button>
</form>

我有两个 js 和 jquery 函数,它们将选择添加到 divCategory。通过这个选择,我可以添加一些类别。

function countMyCategories() {
if (typeof countMyCategories.counter == 'undefined') {
countMyCategories.counter = -1;
}
return ++countMyCategories.counter;
}

$(document).ready(function () {
$('#btnAddCategory').on('click', function () {
var catId = countMyCategories();
$('#divCategory').append(
'<select id="selectCategory' + catId + '" asp
for="@@Model.CatBrands[' + catId + '].CatId" class="mt-3 form-control
form-control-sm">' +
'<option>---Select---</option>' +
'</select>'
);

$.ajax('/API/GetCats')
.done(function (categories) {
for (var i = 0; i < categories.length; i++) {
$('#selectCategory' + catId).append(
'<option value="' + categories[i].id + '">' +
categories[i].name + '</option>'
)
}
});
});
});

当我单击“添加类别”按钮时,一个选择标签通过 id="divCategory"添加到 div,但问题是当我单击“创建新品牌”按钮时,我没有从这些选择中获取数据服务器,实际上 CatBrands 是空的,但我得到了名字。我得到类似的东西:

{name = "LG", catBrands = null}

最佳答案

CatBrands 为空,因为您不能以这种方式从服务器动态添加数据。当页面呈现时,您需要在 html 中由 asp 呈现的所有内容。

<form method="post" enctype="multipart/form-data">
<div>
<label>Brand Name:</label>
<input type="text" asp-for="@Model.Name">
</div>
<div id="divCategory">
<select id="selectCategory asp-code-goes-here>
<option>---Select---</option>
</select>
</div>
<button type="button" id="btnAddCategory">Add Category</button>
<button>Create new Brand</button>
</form>

关于javascript - 如何从添加到 html 页面的动态元素中获取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54487877/

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