简体   繁体   English

jQuery使给定div的所有子链接在新窗口中打开

[英]jQuery to make all child links of a given div open in a new window

I have a div with ID "MyDiv" in which I need all child anchors of this div to open in a new window. 我有一个ID为“ MyDiv”的div,我需要该div的所有子锚在新窗口中打开。

I'm trying: 我正在努力:

jQuery('#MyDiv.children() a').click(function(){
    jQuery(this).attr('target', '_blank');
});

click here for jsFiddle example 单击此处获取jsFiddle示例

$('#MyDiv a').attr ('target', '_blank');

If you are unsure about how this attributes works read up on it below: 如果不确定此属性的工作方式,请阅读以下内容:


If you don't fancy the use of target="_blank" (it's often frowned upon when writing xHTML) you could bind a click event to the anchors and open a new window using javascript/jquery. 如果您不喜欢使用target="_blank" (编写xHTML时常常会皱眉),则可以将click事件绑定到锚点,然后使用javascript / jquery打开一个新窗口。

Such as in the below example: 如下面的示例:

click here for jsFiddle example 单击此处获取jsFiddle示例

$('#MyDiv a').click(function(ev) {
  window.open(this.href);
  ev.preventDefault   (); // see post comment by @nbrooks
});

The problem is the main selector. 问题是主选择器。 .children() is not a valid part of a css selector. .children()不是CSS选择器的有效部分。 If you add a space in the css selector, the following part of the selector will be searched in all child nodes. 如果在css选择器中添加空格 ,则将在所有子节点中搜索选择器的以下部分。 If you want to search in the direct child nodes only, you can use > instead. 如果只想在直接子节点中搜索,则可以改用> Eg replace #MyDiv.children() a with #MyDiv>a : 例如,将#MyDiv.children() a替换为#MyDiv>a

jQuery('#MyDiv>a').click(function(){
    jQuery(this).attr('target', '_blank');
});

or you can use: 或者您可以使用:

jQuery('#MyDiv>a').click(function(oEvent) {
    oEvent.preventDefault();
    window.open($(this).attr('href'), '_blank');
});

you can get rid off the .children() in the selector. 您可以摆脱选择器中的.children()

Markup: 标记:

<div id="MyDiv">
    <a href="http://wwww.google.com">1</a>
    <a href="http://wwww.google.com">2</a>
    <a href="http://wwww.google.com">3</a>
    <a href="http://wwww.google.com">4</a>
</div>​

jQuery: jQuery的:

$('#MyDiv a').click(function(){ 
    $(this).attr('target', '_blank'); 
}); ​

jsFiddle example jsFiddle示例

This may be useful for you 这可能对您有用

$('#MyDiv a').live('click', function() {
    window.open($(this).attr('href'));
    return false;
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM