jQuery to open link in new window not working
I have a dynamic navigation and need to open one link in a new window.
As such I am using jQuery to help, but the following code does not seem to work:
<script type="text/javascript">
$('a[href="ht开发者_如何学Pythontp://globalhealth-dev.oit.duke.edu/education/global-health-courses"]').attr("target", "_blank");
</script>
To try it for yourself: http://globalhealth-dev.oit.duke.edu/education/ then click on the Global Health Courses link under Education.
I would appreciate some help getting this to work properly.
Thanks.
The selection part of your script is wrong, namely the href that should match the href in the element. Try with this:
$('a[href="/education/global-health-courses"]').attr("target", "_blank");
Also note that it is not recommended to select that link using href as it is slower than just using a id in the element and then using $("a#myid").
Also be careful to call this only when the document is done loading:
<script type="text/javascript">
$(document).ready(function() {
$('a[href="/education/global-health-courses"]').attr("target", "_blank");
});
</script>
$(function() {
$('a').attr("target", "_blank");
});
You need to wait for the DOM to be ready. Also placing the actual link attribute doesn't seem like a very maintainable/reusable idea.
It seems your <a>
is this:
<a href="/education/global-health-courses">Global Health Courses</a>
You can try doing a attribute match for "ends with" in the event that the href gets rewritten (which has been known to happen on some browsers) -- Also, you don't need the quotes around the attribute
// Use the "DOM Ready" event to delay execution until the page is loaded
// $(func) is a shortcut for $(document).ready(func)
$(function() {
$('a[href$=/education/global-health-courses]').attr('target', '_blank');
});
It would be much better if you could add a class to the link to identify it as a open in new window link.
精彩评论