[英]How to get the values from dynamically generated html textboxes in asp.net
[英]How to get attribute of dynamically generated element ASP.NET
我知道关于这个话题有很多问题,我已经尝试了很多都无济于事。 如果有人有任何建议,将不胜感激。 我正在尝试获取输入的 id 属性。 我已经剥离了代码,只专注于这个问题。
该cshtml:
@for (var i = 0; i < Model.DieRouteChecks.Count; i++)
{
<div class="col-9">
<div class="form-group newThresholdInput">
<input asp-for="@Model.DieRouteChecks[i].NewDieThresh" class="form-control" id="@Model.DieRouteChecks[i].Description">
</div>
</div>
}
我的JavaScript:
$(".newThresholdInput input").click(() => {
console.log($(this).attr("id")); //To see what's being returned
switch ($(this).attr('id')) {
case "Order Value":
//Do stuff
break;
case "Order Quantity":
//Do stuff
break;
}
})
单击输入时,我不断收到undefined
的记录。 我试过了
$(".newThresholdInput").click(() => {
console.log($(this).find("input").attr("id"));
}
它只打印出第一个输入元素的 id。 我也尝试过使用onclick="function(this)"
并创建一个在脚本标签中调用的事件处理程序,但仍然没有。
有趣的是console.log($(".newThresholdInput input").attr("id"))
记录Order Value
,所以我猜它与我使用$(this)
的方式有关。
我确定我只是错过了一些小东西,但我不知道它可能是什么。
在您的点击事件中, this
代表整个窗口,因此它无法找到您点击的元素。
将您的 js 更改为:
@for (var i = 0; i < Model.DieRouteChecks.Count; i++)
{
<div class="col-9">
<div class="form-group newThresholdInput">
<input asp-for="@Model.DieRouteChecks[i].NewDieThresh" class="form-control" id="@Model.DieRouteChecks[i].Description">
</div>
</div>
}
@section Scripts {
<script>
$(document).on('click', '.newThresholdInput input', function () {
var index = $(this).attr("id");
console.log(index);
});
</script>
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.