简体   繁体   English

如何获取动态生成的元素 ASP.NET 的属性

[英]How to get attribute of dynamically generated element ASP.NET

I know there are tons of questions on this topic and I've tried many of them to no avail.我知道关于这个话题有很多问题,我已经尝试了很多都无济于事。 If anyone has any suggestions, it would be greatly appreciated.如果有人有任何建议,将不胜感激。 I'm trying to get the inputs' id attribute.我正在尝试获取输入的 id 属性。 I've stripped the code to just focus on the issue.我已经剥离了代码,只专注于这个问题。

The cshtml:该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>
}

My javascript:我的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;
            }
        })

I keep getting undefined logged when clicking the input.单击输入时,我不断收到undefined的记录。 I've tried我试过了

$(".newThresholdInput").click(() => {
    console.log($(this).find("input").attr("id"));
}

And it printed out only the first input element's id.它只打印出第一个输入元素的 id。 I've also tried using onclick="function(this)" and creating an event-handler that's called in the script tags but still nothing.我也尝试过使用onclick="function(this)"并创建一个在脚本标签中调用的事件处理程序,但仍然没有。

What's funny is console.log($(".newThresholdInput input").attr("id")) logs Order Value as it should so I'm guessing it has something to do with how I'm using $(this) .有趣的是console.log($(".newThresholdInput input").attr("id"))记录Order Value ,所以我猜它与我使用$(this)的方式有关。

I'm sure I'm just missing something small but I don't know what it might be.我确定我只是错过了一些小东西,但我不知道它可能是什么。

In your click event, this represents the whole Window so that it cannot find your clicked element.在您的点击事件中, this代表整个窗口,因此它无法找到您点击的元素。

Change your js to:将您的 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM