如何仅为特定URL向超链接添加属性

How to add attribute to hyperlink only for specific URLs?

本文关键字:超链接 添加 属性 URL 何仅      更新时间:2023-10-22

我正在尝试为特定URL(知识库)添加一个属性,以便在新的选项卡上打开它。

我的代码:

jQuery("a[href^='http://knowledgebase.sample.net']").attr("target","_blank");

那是我在functions.php:中的脚本

function target_blank_script() {
  // register your script location, dependencies and version
  wp_register_script('target_blank', get_template_directory_uri() . '/js/target_blank.js',array('jquery'), '1.0' );
  // enqueue the script
  wp_enqueue_script('target_blank');
}
add_action('wp_enqueue_scripts', 'target_blank_script');

但这是行不通的。

您的脚本失败了,因为jQuery脚本运行时链接不存在,因为它是在HEAD中加载的。您需要让WP在页面底部加载脚本。

function target_blank_script() {
    wp_eneueue_script(
        'target_blank',
        get_template_directory_uri() . '/js/target_blank.js',
        array('jquery'),
       '1.0'
        true
    };
}
add_action('wp_enqueue_scripts', 'target_blank_script');

键是最后一个参数(true),告诉WP将其加载到页脚中。请注意,如果要立即将脚本排入队列,则不需要注册脚本。