I've seen lots on how to do this with an <a>
tag, and I have no problem doing it with that one, but I can't seem to retrieve the href
attribute of a <link>
tag.
Even trying to grab the link tag at all:
alert($("link").length);
Gives 0.
开发者_如何学CAny ideas?
If $("link").length
is returning 0, your selector isn't coming up with anything and there's no hope for getting the link at all.
You need a better selector. Maybe attack it by ID (#linkId) or by a particular class, etc. There's tons of selectors you can use:
http://api.jquery.com/category/selectors/
Your first step is to get the .length to show 1 though. Then from there .attr('href') will give you the link location.
Edit: Sorry, misinterpreted what you are going for. I was thinking you meant the anchor tag. Here's how I've successfully accessed a link tag:
var links = window.document.getElementsByTagName('link');
$(links).each(function() {
$(this).attr('href') // this is your href for the link tag in the loop
});
My guess is that for some reason the link tag isn't available when you execute your alert statement. When I try the following sample:
<html>
<head>
<link rel="stylesheet src="xxx" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
alert($("link").length);
});
</script>
</head>
<body>
Hello world!
</body>
</html>
It neatly returns "1", not "0". Maybe you could try to figure out the differences between your code and this example. For instance: Are you running your code from the HEAD or from the BODY tag?
精彩评论