简体   繁体   English

如何获取表格行中被点击元素的ID?

[英]How to get the id of a clicked element within a table row?

I have the following table 我有下表

<table width="97%" border="1" class="queueList">
    <thead>
      <tr>
         <th>Delete</th>
         <th>Queue Name</th>
         <th>Current queue length</th>
      </tr>
     </thead>
     <tbody>
            @foreach (var item in Model.ImportQueues)
            {
                <tr id="watchRow">
                    <td id="DeleteButton">X</td>
                    <td id="QueueName", value="@item.QueueName">@item.QueueName</td>
                    <td>@item.CurrentQueueLength</td>
                </tr>
            }
     </tbody>

how can I get the value of the element "QueueName" when "#DeleteRow" is clicked, using JQuery ? 当使用JQuery单击“ #DeleteRow”时,如何获取元素“ QueueName”的值?

So far I have 到目前为止,我有

$("body").on("click", "#DeleteButton", function (event) {    
    var queueName = $(event.target).closest("div.queueList").find("#QueueName");    
    alert(queueName);
}

Without JQuery 没有JQuery

<tr id="watchRow">
  <td class="DeleteButton" onclick="deleteItem(@item.QueueName)">X</td>
  <td value="@item.QueueName">@item.QueueName</td>
  <td>@item.CurrentQueueLength</td>
</tr>

<script>
function deleteItem(item) {
  alert(item)
}
</script>

With JQuery 使用JQuery

<tr id="watchRow">
  <td class="DeleteButton">X</td>
  <td value="@item.QueueName">@item.QueueName</td>
  <td>@item.CurrentQueueLength</td>
</tr>

<script>
    $(".DeleteButton").on("click", function() {
      alert($(this).next("td").html());
    }
    </script>
</script>

Use the data attribute to store the desired value on the button itself 使用data属性在按钮本身上存储所需的值

<tr class="watchRow">
   <td class="DeleteButton" data-queuename="@item.QueueName">X</td>
   <td class="QueueName">@item.QueueName</td>
   <td>@item.CurrentQueueLength</td>
</tr>

then on click of TD (by the way, it should be a button) 然后点击TD(顺便说一句,应该是一个按钮)

$("body").on("click", ".DeleteButton", function() {    
    var queueName = $(this).data("queuename");    
    alert(queueName);
}

If you want to use this name on other buttuns also, like edit etc. then it is better to assign it to the whole row: 如果您还想在其他按钮上使用此名称,例如edit等,那么最好将其分配给整个行:

<tr class="watchRow" data-queuename="@item.QueueName">
   <td class="DeleteButton">X</td>
   <td class="QueueName">@item.QueueName</td>
   <td>@item.CurrentQueueLength</td>
</tr>

and read it like this: 并像这样阅读:

$("body").on("click", ".DeleteButton", function() {    
    var queueName = $(this).closest('tr').data("queuename");    
    alert(queueName);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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