簡體   English   中英

Javascript / jquery在表中單擊按鈕獲取行ID

[英]Javascript/jquery Get Row Id on button click in a table

我是javascript的新手,所以我嘗試在按鈕click上獲取選定的行ID。我不確定我是否在Internet上嘗試過示例,但無法運行代碼。

<tr>
 <input type="hidden" name="InterestID" id="InterestID" value="@info.InterestID" />

       <th>
           <input data-required="true" class="input-sm form-control datepicker" size="16" type="text" name="ValidDate" id="ValidDate" value="@info.ValidDate.ToShortDateString()" />
       </th>
       <th>
           <input class="form-control" data-required="true" name="Rate" id="Rate" value="@info.Rate" />
       </th>
       <th>
           <button type="button" class="btn btn-sm btn-danger" onclick="DeleteInterest()">Delete</button>
       </th>
</tr>

function DeleteInterest(parameters) {
    alert("Delete Button clicked");
}

當我單擊“刪除”按鈕時 ,我想獲取所選行的@ info.InterestId 。那么如何使用javascript / jquery在“刪除”按鈕上單擊以獲取所選行ID?

任何幫助將不勝感激。

謝謝。

您可以嘗試將@ info.InterestID傳遞給DeleteInterest:

HTML:

<button type="button" class="btn btn-sm btn-danger" onclick="DeleteInterest(@info.InterestID)">Delete</button>

和Javascript

function DeleteInterest(id) {
    alert("Delete Button clicked with id " + id);
}

希望有幫助!

如Ruben所說,按如下所述使用,如果不將id傳遞給函數,則無法直接獲取。

 <button type="button" class="btn btn-sm btn-danger" 
       onclick="DeleteInterest('@info.InterestID')">Delete</button>

 function DeleteInterest(id) {
   alert("Delete Button clicked with id " + id);
 }

或者您可以得到如下內容,無需更改HTML

 function DeleteInterest() {
   alert("Delete Button clicked with id " + $("#InterestID").val());
 }

我將動態獲取值:

var DeleteInterest = function(e) {
    alert(this.parentNode.parentNode.getElementsByClassName("value")[0].value);
}

和HTML:

<tr>
 <input type="hidden" class="value" name="InterestID" id="InterestID" value="@info.InterestID" />
       <th>
           <input data-required="true" class="input-sm form-control datepicker" size="16" type="text" name="ValidDate" id="ValidDate" value="@info.ValidDate.ToShortDateString()" />
       </th>
       <th>
           <input class="form-control" data-required="true" name="Rate" id="Rate" value="@info.Rate" />
       </th>
       <th>
           <button type="button" class="btn btn-sm btn-danger" onclick="DeleteInterest(this)">Delete</button>
       </th>
</tr>

我什至認為在js中將按鈕與value元素匹配而不是將其隱藏在html中的哈希表中而不是將其隱藏在html中更為有趣,那么,您應該具有:

var list = {<button_html_node_element>: '@info.InterestID'} 

然后,您的刪除功能:

var DeleteInterest = function(e) {
    alert(list[e]);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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