[英]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.