[英]Get the href target of a link and manipulate element with same name using Jquery
這可能很容易,但是即使弄清楚我要從哪里開始,我也沒有運氣。 這個想法是我有一個頁面,我將jquery放在上面……該jquery將在表中查找鏈接,獲取href(或更確切地說是url的一部分,因為它們鏈接到同一頁面上的元素),然后搜索以名稱命名元素,以便我可以對其進行操作。 或者,如果您能想到一種更好的方法。
換句話說,我希望做的是使用鏈接的URL中的信息來查找元素...我希望我已經清楚了...>。>
使用.attr('href');
得到目標。
我猜你想做這樣的事情:
<table>
<tr><td><a href="/items/1/order">Item 1</a></td></tr>
<tr><td><a href="/items/2/order">Item 2</a></td></tr>
</table>
<script>
$('table tr').each(function () {
var id = $('a', this).attr('href').match(/^\/items\/(\d+)\/order$/)[1];
$(this).append('<td><a href="/items/'+id+'"/edit">Edit</a></td>');
});
</script>
這會將新的表格單元格附加到每行,並帶有鏈接以編輯適當的項目。 您可以使用id
做任何您想做的事,所以可以做類似$('#item-'+id).text('replaced!')
事情。
如果您不熟悉正則表達式( "/items/1/order".match(/^\\/items\\/(\\d+)\\/order$/)[1]
位),則應該閱讀一下它們 。
這應該做你指定的
$().ready(function() {
// For each link in any table
$('table a').each(function(i) {
// determine the anchors name
var name = $(this).attr('href').match(/#(.*)$/)[1];
// Select all anchors with name that matches the #<name>
// We use the selector a[name="<name>"], double quotes are
// used to protect from white space characters in links
var target = $('a[name="' + name + '"]');
// manipulate
target.html('lorem ipsum dolor sit amet');
});
});
如果您能夠修改頁面,則可以不依賴正則表達式,而可以向包含類名或錨點所在元素的ID的鏈接插入其他屬性。 瀏覽器的確為您提供了許多自由,可以為HTML標准中未指定的元素添加額外的屬性。 HTML5甚至允許它們使用,請參閱自定義屬性-是或否? 。
基本上,自定義屬性在渲染時會被忽略,但仍會添加到DOM中。 當它們駐留在DOM中時,您可以根據需要訪問和使用它們。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.