简体   繁体   中英

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 ?

So far I have

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

Without 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

<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

<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)

$("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:

<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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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