Use HTML/CSS/Javascript to open links in new pages
I have a div that is represented in multiple pa开发者_C百科ges across my site. I don't want to set each one specifically to open in a new window, rather I want all links in that specific div to open in a new window. How can I do this using HTML/ CSS/ javascript?
Thanks
here's how you could do that with jQuery
if you have something like <div class="myLinks">...</div>
$('.myLinks a').attr("target", "_blank");
Well, I guess there are two reasonable ways to open the href from an anchor in a new window.
- Edit the
node
and set itstarget
to_blank
(<a href="foo" target="_blank"></a>
) Use Javascript to catch the click event, prevent the default behavior and call
window.open()
var anchors = document.querySelectorAll('#mydiv a'); [].forEach.call(anchors, function(anchor) { anchor.addEventListener('click', function(e) { window.open(e.target.href, 'mywindow', '_blank'); e.preventDefault(); e.stopPropagation(); }, false); });
That example code is vanilla Javascript and it'll only work in a W3C compliant browser (!= IE).
If you can afford to you use a JS framework live is going to be easier since all of those will abstract browser differences for you.
I think you have a div and link like this in some pages:
<div id="myDiv">
<a href="Link Url">Link Text</a>
<!--some other elements-->
</div>
you need to create a js file like bellow and add it to end of all of your pages :
var div = document.getElementById("myDiv");
if (div) {
for (var i = 0; i < div.childNodes.length; i++)
{
if (div.childNodes[i].nodeName.toLowerCase() == "a")
div.childNodes[i].target = "_blank";
}
}
And its all things you need to do ! this code is fast enough and even does not need JQuery.
Couldn't you use jQuery to iterate through all links within a specified div, then set the target to "_blank".
You can use javascript and jQuery.
First of all I suggest that DIV have id outgoing
.
<div id='outgoing'>
<a href='http://google.com'>Go to Google</a><br>
<a href='http://stackoverflow.com'>Look at SO!</a>
</div>
Now we can use simple JavaScript to dynamiclaly add target='blank'
into these links:
$(function() {
$('#outgoing a').attr('target', '_blank');
});
You can check example here
精彩评论