问题描述
我有一个带有文本没有新通知"的链接.以下代码用于使链接不可点击:
I have a link with the text "No New Notifications". The following code is used to make the link not clickable:
if ($.trim($('a#full_notifications_link').text()) == "No New Notifications"){
$('a#full_notifications_link').click(function(){
event.preventDefault();
return false;
});
}
我正在使用Ajax轮询服务器并更新文本.当文字更新为查看所有通知"时,我希望链接变为可点击的.我正在使用以下代码,但无法正常工作.
I am using Ajax to poll the server and update the text. When the text is updated to say "See All Notifications", I want the link to become clickable. I am using the following code, but it is not working.
$(document).ajaxComplete(function(){
if ($.trim($('a#full_notifications_link').text()) == "See All Notifications"){
$('a#full_notifications_link').click(function(){
return true;
});
}
});
我知道问题与返回true有关,因为如果我在返回true之前就将警报放入,则警报有效.不幸的是,该链接仍然不可点击.
I know the problem has something to do with returning true, because if i put an alert in right before returning true, the alert works. Unfortunately, the link is still unclickable.
我也无法更改任何html,因为后端每次生成的HTML都不一样.
I also CANNOT change any of my html because it is generated differently every time by the backend.
推荐答案
添加新的事件处理程序不会删除您已有的事件处理程序,因此仍会阻止默认操作.
Adding a new event handler does not remove the event handlers you already have, so the default action is still prevented.
改为使用on()
和off()
if ($.trim($('a#full_notifications_link').text()) == "No New Notifications"){
$('a#full_notifications_link').on(function(event){
event.preventDefault();
});
}
$(document).ajaxComplete(function(){
if ($.trim($('a#full_notifications_link').text()) == "See All Notifications"){
$('a#full_notifications_link').off('click');
}
});
仅检查事件处理程序中的文本似乎更容易
It does seem easier to just check the text inside the event handler
$('a#full_notifications_link').on('click', function(e) {
if ( $.trim($(this).text()) == "No New Notifications"){
e.preventDefault();
}
});
这篇关于在使用preventDefault之后尝试重新启用链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!