如何使用realhref将处理程序设置为所有链接

How to can i set handlers to all links with real href?

本文关键字:链接 设置 程序 何使用 realhref 处理      更新时间:2023-09-26

我使用jQuery 2.1.1,我有这样的代码:

//Load and execute script via AJAX
function loadScript(e) {
        $.getScript($(e.target).attr("href")).error(function (error) {
            $.notify("Request error"); 
        });
    return false; //Cancel opening link in the browser
}
//Set handlers to all <a> elements with href attribute and href!='#'
Desktop.prototype.init = function () {
    $("body").on("click", $("a[href][href!='#']"), {}, loadScript);
};

当我点击文档的某个位置时,我会看到错误消息(404)。为什么?在这种情况下我应该写什么?我将通过单击<a>标记来动态加载和执行脚本。

您可以使用以下语法对href值不为#的锚元素进行事件委派。

$('body').on('click', 'a:not([href="#"])', loadScript);

这是一个正在工作的jsFiddle