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&l开发者_StackOverflowt;/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?
Change eq(2)
to eq(1)
, because eq()
starts from index 0
and also make sure you change attributes after DOM is ready
<html>
<script>
$(function(){ $("a:eq(1)").attr("target", "_blank"); });
</script>
<body>
<a href="http://cnn.com">CNN</a><br />
<a href="http://google.com">Google</a>
</body>
</html>
Wait until after the link actually exists before trying to modify it and start counting from 0
not 1
.
(Untested):
<html>
<body>
<a href="http://cnn.com">CNN</a><br />
<a href="http://google.com">Google</a>
<script>
$("a:eq(1)").attr("target", "_blank");
</script>
</body>
</html>
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 1
$(function(){
// wait for the DOM to load.
$("a").eq(1).attr("target", "_blank");
});
Look here for reference http://api.jquery.com/eq/
Here is a working example based on your code. http://jsfiddle.net/3wz9a/2/
精彩评论