使用 Jquery 打开页面上的第二个链接
我正在尝试使用 Jquery 在新页面中打开我的页面上的链接。
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("a:eq(0)").attr("target","_blank");
});
</script>
</head>
<body>
<h1>Welcome to My Homepage</h1>
<p class="intro">My name is Donald</p>
<a href="http://google.com">I live in Duckburg</a>
<p>My best friend is Mickey</p>
Who is your favourite:
<ul id="choose">
<li>Goofy</li>
<li>Mickey</li>
<li>Pluto</li>
</ul>
</body>
</html>
(上次编辑时复制了错误的代码,这是我现在使用的代码。这是在页面加载时通过 JavaScript 执行的,该 JavaScript 调用了一堆其他加载时的东西。)
我有所有其他代码到位,但这仍然无法正常工作。
但此代码仍会在同一窗口中打开第二个链接。有人可以帮忙吗?
I am trying to open a link on my page in a new page with Jquery.
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("a:eq(0)").attr("target","_blank");
});
</script>
</head>
<body>
<h1>Welcome to My Homepage</h1>
<p class="intro">My name is Donald</p>
<a href="http://google.com">I live in Duckburg</a>
<p>My best friend is Mickey</p>
Who is your favourite:
<ul id="choose">
<li>Goofy</li>
<li>Mickey</li>
<li>Pluto</li>
</ul>
</body>
</html>
(copied wrong code on last edit this is the code I am using now. This is executed at page load time via a javascript that calls a bunch of other load time things.)
I have all the other code in place, and this continues to not work properly.
But this code still opens the second link in the same window. Can anyone help?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
将
eq(2)
更改为eq(1)
,因为eq()
从索引0
开始,并且还使确保在 DOM 准备好后更改属性Change
eq(2)
toeq(1)
, becauseeq()
starts from index0
and also make sure you change attributes after DOM is ready等到链接实际存在之后再尝试修改它,并从
0
而不是1
开始计数。(未经测试):
Wait until after the link actually exists before trying to modify it and start counting from
0
not1
.(Untested):
eq
引用一个元素数组。数组以索引 0 开头,因此您需要查找索引为 1 的元素请参阅此处 http://api.jquery.com/eq/
这是一个基于您的代码的工作示例。 http://jsfiddle.net/3wz9a/2/
eq
references an array of elements. Arrays start with the index of 0, so you will want to look for the element with an index of 1Look here for reference http://api.jquery.com/eq/
Here is a working example based on your code. http://jsfiddle.net/3wz9a/2/