[英]jQuery to make all child links of a given div open in a new window
我有一个ID为“ MyDiv”的div,我需要该div的所有子锚在新窗口中打开。
我正在努力:
jQuery('#MyDiv.children() a').click(function(){
jQuery(this).attr('target', '_blank');
});
$('#MyDiv a').attr ('target', '_blank');
如果不确定此属性的工作方式,请阅读以下内容:
如果您不喜欢使用target="_blank"
(编写xHTML时常常会皱眉),则可以将click事件绑定到锚点,然后使用javascript / jquery打开一个新窗口。
如下面的示例:
$('#MyDiv a').click(function(ev) {
window.open(this.href);
ev.preventDefault (); // see post comment by @nbrooks
});
问题是主选择器。 .children()
不是CSS选择器的有效部分。 如果在css选择器中添加空格 ,则将在所有子节点中搜索选择器的以下部分。 如果只想在直接子节点中搜索,则可以改用>
。 例如,将#MyDiv.children() a
替换为#MyDiv>a
:
jQuery('#MyDiv>a').click(function(){
jQuery(this).attr('target', '_blank');
});
或者您可以使用:
jQuery('#MyDiv>a').click(function(oEvent) {
oEvent.preventDefault();
window.open($(this).attr('href'), '_blank');
});
您可以摆脱选择器中的.children()
。
标记:
<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的:
$('#MyDiv a').click(function(){
$(this).attr('target', '_blank');
});
这可能对您有用
$('#MyDiv a').live('click', function() {
window.open($(this).attr('href'));
return false;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.