javascript JQuery 选择器问题——如何找到目标 = _blank 的所有 HREF?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7507009/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 00:21:41  来源:igfitidea点击:

JQuery Selector Question -- How to find all HREF's with a target = _blank?

javascriptjqueryselector

提问by Jason S. Burton

My "JQuery Selector Foo" stinks. I need to find all HREF's with a target attr of _blank and replace them with a common window/target. Assistance is greatly appreciated!

我的“JQuery Selector Foo”很糟糕。我需要找到目标属性为 _blank 的所有 HREF,并将它们替换为通用窗口/目标。非常感谢您的帮助!

回答by Ry-

$("a[target='_blank']").attr('target', 'sometarget');

Do you mean something like that?

你的意思是这样吗?

回答by ravy amiry

try

尝试

        $("a[target=_blank]").each(function () {
            var href = $(this).attr("href"); // retrive href foreach a
            $(this).attr("href", "something_you_want"); // replace href attribute with wich u want
            // etc
        });

let me know what do you want, for more help

让我知道你想要什么,以获得更多帮助

回答by JaredPar

If you're specifically looking for hrefvalues which have blank values then do the following

如果您专门寻找href具有空白值的值,请执行以下操作

$('a[href=""]').each(function() {
  $(a).attr('href', 'theNewUrl');
});

This will catch only anchor tags which have a href attribute that is empty. It won't work though for anchors lacking an href tag

这将仅捕获具有空的 href 属性的锚标记。但是对于缺少 href 标签的锚点,它不起作用

<a href="">Link 1</a> <!-- Works -->
<a>Link 2</a> <!-- Won't work -->

If you need to match the latter then do the following

如果您需要匹配后者,请执行以下操作

$('a').each(function() {
  var href = $(this).attr('href') || '';
  if (href === '') {
    $(this).attr('href', 'theNewUrl');
  }
});