最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Make links in a specific div open in new tab - Stack Overflow

programmeradmin5浏览0评论

I want to open links in my post on a new page or a new tab rather. But only the link in the specific division, not all the links on my page. I don't wanna put _blank in all my tags it's too time consuming. How can I do that?

Thanks in advance.

I want to open links in my post on a new page or a new tab rather. But only the link in the specific division, not all the links on my page. I don't wanna put _blank in all my tags it's too time consuming. How can I do that?

Thanks in advance.

Share Improve this question asked Nov 12, 2010 at 4:41 AayushAayush 3,09810 gold badges50 silver badges73 bronze badges 2
  • @ayush specific division means?? you mean certain links. please let me know if they are a href or div clicks.There are multiple ways to do that. – kobe Commented Nov 12, 2010 at 4:47
  • @ayush , if the answer given by others fixes your problem mark that as answer.So that they will respond fast in future for the questions and help everyone. – kobe Commented Nov 12, 2010 at 5:20
Add a ment  | 

3 Answers 3

Reset to default 15

With jQuery, you could set the target to _blank for all your links. E.g.

$(function(){
  $("#myDiv a").attr("target","_blank");
});

Example on jsFiddle.

You really ought to put them in. If it's too time-consuming, try using a simple regex to do it for you (only run it on the html you care about). Replace:

(<a href[^>]*)(>)

with

$1 target="_blank"$2

If you really need to, you can use JavaScript, but it won't work where javascript is disabled. It's really a terrible solution for this problem:

var el = document.getElementById('myDiv'); // or some other way of making `el` point to your element
var links = el.getElementsByTagName('a');
for( var i = 0; i < links.length; i++ )
{
  links.target = '_blank';
}

Here is a link to the Javascript that I use to set all the links within a certain div (or all links which are labeled with a certain class) to open in a new window: http://icode4you/use-javascript-to-open-all-links-within-a-certain-div-in-a-new-window.

I originally found this script at http://www.dynamicdrive./dynamicindex8/newwindow3.htm

发布评论

评论列表(0)

  1. 暂无评论