2010-05-26 86 views
1

即使以下工作: http://jsfiddle.net/N7D5r/

我在使用相同的代碼不能正確獲得冠軍嘗試。無論出於何種奇怪原因,它們都返回null:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> 
<script type="text/javascript"> 
$(document).ready(function(){ 
    // Act on each link 
    $('a').each(function(eachIteration){ 

     // Store current link's url 
     var url = $(this).attr("href"); 

     $.get(url, function(response){ 
      alert("This is the url: " + url); 
      if (((/<title>(.*?)<\/title>/m).exec(response)) != null) 
       alert("This would be the title: " + (/<title>(.*?)<\/title>/m).exec(response)[1]); 
      else 
       alert("title was null"); 
     });   

    }); 
}); 
</script> 
<title>test</title> 
</head> 

<body> 
<p><a href="javascript:;">Javascript link</a></p> 
<p>&nbsp;<a href="http://www.latentmotion.com">Misc. Link</a> and what else... <a href="http://www.latentmotion.com/how-to-create-a-jquery-bookmarklet/#comment-52004762">jQuery Bookmarklet Link</a></p> 
<p> Some <a href="#test">anchor link</a> test.</p> 
</body> 
</html> 

任何想法?


注: 這個問題是在位於這裏的堆棧溢出問題的後續行動: jQuery Can't $(...).load() the head title in Chrome

+0

它不起作用?整個「迴應」是什麼樣的?代碼是否說標題爲空,還是會給出錯誤的結果? – Pointy 2010-05-26 18:55:12

+0

此代碼適用於我,只是粘貼到一個新的HTML頁面。你是否試圖在本地運行它?如果是這樣,您可能需要允許它訪問外部內容。 – 2010-05-26 18:58:43

+0

由於它不工作,我的意思是它沒有從鏈接中獲得標題。即使網址確實有標題,它仍在運行「標題爲空」。 – Matrym 2010-05-26 19:03:11

回答

1

This is the url: /users/recent/205784 This would be the title: User antimatter15 - Recent - Stack Overflow This is the url: /about This would be the title: About - Stack Overflow This is the url: /faq This would be the title: FAQ - Stack Overflow This is the url: /users/205784/antimatter15

您的代碼似乎工作。難道這些鏈接超出了當前域名並違反了同源策略?

+0

同樣的域名,在這裏測試:http://latentmotion.com/bookmarklets/link-checker/test.html – Matrym 2010-05-26 19:07:05

+0

DOH!這是一個沒有www的子域問題,我認爲。 – Matrym 2010-05-26 19:07:36