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

How to add attribute to hyperlink only for specific URLs?

我正在尝试为特定 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');

但这不起作用。

您的脚本失败,因为 link 在 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 将它加载到页脚中。请注意,如果您要立即入队,则无需注册脚本。