[英]jquery - using selector to find an href
背景資料:
我正在嘗試在href的屬性“ row_id”中查找值。 當用戶單擊“保存更改”按鈕/圖像時,將觸發此邏輯。
問題描述
我現在擁有的jQuery代碼將返回第二個單元格的內容,而不是其中包含href的那個。 因此,從下面的HTML示例代碼中,我需要從中提取21586
"<a href="index.php?page=row&row_id=21586">Row SAA:HH1</a>"
HTML代碼
觸發jquery邏輯的按鈕在該行的第4個單元格中,並且row_id在第5個單元格的href中。
<tr>
<td id="21581">
<img src="?module=chrome&uri=pix/tango-user-trash-16x16-gray.png" title="1 rack(s) here" height="16" width="16" border="0">
</td>
<td><div id="location_name">SAA:HH-123</div></td>
<td><div id="row_name">SAA:HH1</div></td>
<td>
<input tabindex="1" name="edit" class="edit" src="?module=chrome&uri=pix/pencil-icon.png" id="21581" title="Edit row" type="image" border="0">
<input tabindex="1" style="display: none;" name="submit" class="icon" src="?module=chrome&uri=pix/tango-document-save-16x16.png" title="Save changes" type="image" border="0">
</td>
<td>
<a href="index.php?page=row&row_id=21586">Row SAA:HH1</a>
</td>
</tr>
jQuery代碼
//save button handler
$(".icon").click(function(e){
//find the <a href that has the row id embbeded in it
var row_id = $(this).parent().siblings().children($('a[href$="row_id"]'));
console.log($(row_id).text());
});
任何建議,將不勝感激。
您可以嘗試以下方法:
$(".icon").click(function(e){
//find the <a href that has the row id embbeded in it
var row_link = $(this).parent().siblings().find('a[href*="row_id"]')
var row_id = row_link.attr('href').split('row_id=')[1];
console.log(row_id);
});
檢查控制台,它返回21586。我使用.closest()
和.find()
進行導航並在對應的行中找到<a>
。 然后我得到了href
屬性並將其拆分以找到所需的id
$(document).ready(function() { $('.icon').on('click', function() { var href = $(this).closest('tr').find('a').attr('href'); var id = href.split('&')[1].split('=')[1]; console.log(id); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tr> <td id="21581"> <img src="?module=chrome&uri=pix/tango-user-trash-16x16-gray.png" title="1 rack(s) here" height="16" width="16" border="0"/> </td> <td><div id="location_name">SAA:HH-123</div></td> <td><div id="row_name">SAA:HH1</div></td> <td> <input tabindex="1" name="edit" class="edit" src="?module=chrome&uri=pix/pencil-icon.png" id="21581" title="Edit row" type="image" border="0"/> <input tabindex="1" style="" name="submit" class="icon" src="?module=chrome&uri=pix/tango-document-save-16x16.png" title="Save changes" type="image" border="0"/> </td> <td> <a href="index.php?page=row&row_id=21586">Row SAA:HH1</a> </td> </tr> </table>
嘗試使用以下
var result = $('a[href]',$(this).parent().parent()).attr('href').split("=").pop();
//結果將等於21586
嘗試這個 。 可以普遍用於任何url和參數值。
$.getUrlParamValue = function(link, parameter){
var results = new RegExp('[\?&]' + parameter + '=([^&#]*)').exec(link);
return results[1] || 0;
}
var value = $.getUrlParamValue ($("a").attr("href"),'row_id');
alert(value);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.