簡體   English   中英

如何獲取動態生成的元素 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM