0

I have twp problems

Mark up for the link

                <a href="/Home/DisplaySpreadSheetData" id="displaySpreadSheetLink">DisplaySpreadsheetData</a>

1) Under document.ready i have this line of code to make sure the link is disabled by default but it does not work.

        $('#displaySpreadSheetLink').bind('click', disableLink);

Code to disable the link

    var disableLink = function (e) {       
    e.preventDefault();
    return false;      
    }

2) when the link is clicked i want to make sure that if checkFile() returns true the link should be disabled

    $('#displaySpreadSheetLink').click(function (e) {
        if (checkFile()) {          
        e.preventDefault();
    }      
});

There are two problems here. How can i correct the first problem and for the second one i think e.preventDefault() does not get executed even if checkFile() returns true. Can anyone help please?

4

2 回答 2

1

您可能会遇到问题,因为您实际上已将两个点击事件绑定到您的链接。您应该disableLink在绑定新功能之前取消绑定该功能:

function disableLink(e) {
    e.preventDefault();
    // don't use return false here.
}

$(function() {
    $('#displaySpreadSheetLink').click(disableLink);
});

// later on

$('#displaySpreadSheetLink').unbind('click').click(function (e) {
    if (checkFile()) {
        e.preventDefault();
    }      
});

另外,请仔细检查您的逻辑checkFile()。仅基于我假设的名称,以前从未见过您的代码,您希望阻止默认行为 if checkFile() failed。你确定不想要if (!checkFile()) { ... }

另一种方法可能是只处理单个事件,但要考虑一些额外的状态信息,以确定是否应该执行默认行为:

(function($) {
    var loaded = false;
    $('#displaySpreadSheetLink').click(function(e) {
        if (!loaded || checkFile()) {
            e.preventDefault();
        }
    });
    $(function() {
        loaded = true;
    });
})(jQuery);
于 2013-07-01T14:46:25.710 回答
0

与其在页面加载后禁用带有函数的链接,不如使用<span>看起来像禁用链接的 CSS 类来更改最初禁用的 HTML。

checkFile()不要在用户每次点击链接时调用,而是在可以改变checkFile()istruefalse. 例如,如果在文件上传后checkFile()变为,则true在文件上传函数中放入代码以通过将 替换为 来启用链接<span>,并在可能再次变为<a>的适当位置放置链接禁用代码。checkFile()false

仅仅使用preventDefault()会使链接看起来可点击,如果它实际上什么都不做,这可能是糟糕的 UI 设计。

于 2013-07-01T14:52:43.233 回答