如何将处理程序设置为具有真实href的所有链接?

时间:2014-10-31 08:54:05

标签: javascript jquery ajax jquery-selectors handler

我使用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>标记动态加载和执行脚本。

1 个答案:

答案 0 :(得分:0)

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

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

Here's a working jsFiddle