简体   繁体   English

我如何获得 <link> 使用jQuery标签?

[英]How can I get the href of a <link> tag using jQuery?

I've seen lots on how to do this with an 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. 我已经看到了很多关于如何使用标签执行此操作的方法,并且使用该标签执行操作没有问题,但是我似乎无法检索<link>标签的href属性。

Even trying to grab the link tag at all: 甚至尝试完全获取链接标记:

alert($("link").length);

Gives 0. 给出0。

Any ideas? 有任何想法吗?

Thanks, 谢谢,
Matt 马特

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. 如果$("link").length返回0,则说明您的选择器没有任何提示,根本没有希望获得链接。

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: 也许可以通过ID(#linkId)或特定类等对其进行攻击。您可以使用大量的选择器:

http://api.jquery.com/category/selectors/ http://api.jquery.com/category/selectors/

Your first step is to get the .length to show 1 though. 第一步是让.length显示为1。 Then from there .attr('href') will give you the link location. 然后从那里.attr('href')将为您提供链接位置。

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". 它整洁地返回“ 1”,而不是“ 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? 例如:您是从HEAD还是从BODY标记运行代码?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM