将页面上的所有a
元素设置为target="_blank"
是一个简单的jQuery行:$("a").attr("target", "_blank");
但我无法弄清楚如何有选择地做到这一点。我希望将所有元素a
目标设置为_blank
,但具有id="self"
的目标除外。
到目前为止,我有以下非功能性代码。我在正确的道路上吗?
$("a").attr("target", function(val){if ($(this).attr("id") == "self") {return "_self";} else {return "_blank";}});
答案 0 :(得分:3)
有很多方法可以做到这一点,一个是:
$("a").not("#self").attr("target", "_blank");
如果你想弄清楚如何做一些新的事情,你可以随时查看jQuery docs。
附注:页面上的多个元素具有相同的id
无效,因此请确保您没有id="self"
的两个元素。
答案 1 :(得分:2)
有一种.not方法专门用于从选择中排除元素(或元素集合)。
$("a").not("#self").attr("target", "_blank");
答案 2 :(得分:1)
使用each方法:
$('a').each(function(){
if($(this).attr('id')=='self'){
return $(this).attr('target','self');
} else{
return $(this).attr('target','_blank');
}
});
但我建议使用class而不是像这样简单地检查id:
$('a').each(function(){
if(!$(this).hasClass('self')){
return $(this).attr('target','_blank');
}
});
答案 3 :(得分:1)
最简单的方法之一就是选择器本身如下:
$('a[id!="self"]').attr("target", "_blank");
更灵活的方法是使用jQuery的过滤方法:
$('a').filter(function(){
return $(this).attr('id') != 'self'; // Returning false means the element will not be used.
}).attr("target", "_blank");
答案 4 :(得分:0)