首页 > 解决方案 > 有没有更优化的方法来编写这个 _blank 属性到目标链接(在新选项卡中打开它们)的 jQuery 代码?

问题描述

这是我正在使用的代码。这是编写它的最佳方式吗?我能做得更好吗?

// Open External URLs and PDFs in New Tab
$(document).ready(function () {
    $(document).on("click", 'a[href^="http"]', function () {
        $(this).attr("target", "_blank");
    });
    $(document).on("click", 'a[href$=".pdf"]', function () {
        $(this).attr("target", "_blank");
    });
});

标签: jqueryattributeshref

解决方案


您可以将选择器组合成一个事件监听器

$(document).on("click", 'a[href^="http"], a[href$=".pdf"]', function () {
    $(this).attr("target", "_blank");
});

推荐阅读