我正在尝试检索链接的 URL 标题。
例如获取标题:
<a class="stack" href="http://stackoverflow.com" title="Stack Overflow">
将由如下内容动态生成:$('.stack').attr("title", "....");
.
是否可以使用 javascript 或 jQuery 检索 URL 的标题?
非常感谢
最佳答案
花了一点时间来制作,但是这个例子允许你从你的网页下载一个网页。然后从标题标签中提取标题。
<html>
<head>
<!-- jQuery include -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<!-- This include allows cross domain get requests -->
<script type="text/javascript" src="https://raw.github.com/jamespadolsey/jQuery-Plugins/master/cross-domain-ajax/jquery.xdomainajax.js"></script>
<!-- Sample -->
<script type="text/javascript">
$(document).ready(function(){
//gets the href of the first anchor
var url = $("a").first().attr("href");
//sets a get request to get the html source
$.get(url, function(data){
//uses get string between function to get the text between the title tags
//then calls it in a message box
alert(getStringBetween(data.responseText, "<title>", "</title>"));
});
});
function getStringBetween(input, start, end){
var index = input.indexOf(start);
if(index != -1){
index += start.length;
var endIndex = input.indexOf(end, index + 1);
if(endIndex != -1)
return input.substr(index, endIndex - index);
}
return false;
}
</script>
</head>
<body>
<a href="http://www.google.com/">Google</a>
</body>
</html>
关于javascript - 获取网站标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8059464/