[英]Getting all of links from page after load content with jquery load();
將內容加載到頁面后使用
div.load('page.php');
我需要從頁面獲取所有鏈接才能更改它們。 所以我這樣寫:
div.load('page.php', function() {
links = $('a');
alert(links.length);
for(i=0 ; i<links.length ; i++
{
link = $('a:nth-child('+(i+1)+')');
alert(link.attr('href'));
}
});
這段代碼的結果是:-第一個alert()返回了正確的鏈接數量,但是它不是DOM對象,因此我無法使用它來更改href屬性:links [i] .attr('href','changed')而且我必須逐個循環獲取鏈接,但是此方法僅返回了page.php中的第一個鏈接以及站點中的所有鏈接(不會更改)。
有人知道怎么做嗎?
您可以像這樣:
div.load('page.php', function() {
$('a').each(function(index){
alert($(this).attr('href'));
});
});
您可以像這樣更改其href
:
div.load('page.php', function() {
$('a').each(function(index){
$(this).attr('href', 'whatever');
});
});
如果您只需要修改已加載內容中的所有鏈接,請使用context ,如下所示:
div.load('page.php', function(data) {
$('a', data).attr('href', '#');
});
//or, if they're interdependently changed, something like this...
div.load('page.php', function(data) {
$('a', data).attr('href', function(i, href) {
return href + "?tracking=1"; //append ?tracking=1
});
});
這將找到所有<a>
,但僅找到針對page.php
返回的響應,因此僅找到您剛剛加載的錨點。 格式為$(selector, context)
,如果不使用context
,則為document
,因此類似$('a')
東西實際上是$(document).find('a')
,為其提供除document
其他上下文,您說的是$(data).find('a')
,只獲取您想要的鏈接。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.