如何防止默认和禁用一个href
How to preventDefault and disable a href
在第一次点击我的按钮点击功能工作,但再次点击它刷新页面点击取消绑定不被识别。我需要防止任何默认的点击事件以及禁用按钮后点击。
<a href="" class="red-btn2">Save this Property</a>
$(".red-btn2").click(function(event){
event.preventDefault();
$(this).unbind('click');
$(this).css({
'background-color':'#666666',
'text-align':'center'
});
$(this).text("Added to Favorites");
});
如果您需要处理程序的其余部分只运行一次,但preventDefault()
总是运行,您可以将它们分成多个处理程序。
然后,其中一个可以在第一次使用后被删除(使用jQuery的.one()
将为您覆盖),仍然留下使用的preventDefault()
:
$('.red-btn2')
.click(function (event) {
event.preventDefault();
})
.one('click', function () {
$(this).css({
'background-color':'#666666',
'text-align':'center'
});
$(this).text("Added to Favorites");
});
正如您所拥有的,event.preventDefault()
也被.unbind('click')
删除,因此在元素上没有留下任何函数来调用它进行第二次单击。
当您解除绑定处理程序时,该按钮将在任何后续单击中正常运行,并启动导航。所以你最好设置disabled属性:
$(".red-btn2").click(function(event){
event.preventDefault();
if ($(this).prop('disabled')) return; // <---
$(this).prop('disabled', true); // <----
$(this).css({
'background-color':'#666666',
'text-align':'center'
});
$(this).text("Added to Favorites");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="" class="red-btn2">Save this Property</a>
注意event.preventDefault()
实际上工作。只有在第二次点击时你才会遇到问题,因为链接仍然是可点击的,但是你的功能与它分离了,所以你无法控制第二次点击。
相关文章:
- CSS 在悬停时使图像变暗 - 在其周围添加一个 href
- 使用 Javascript 在运行时禁用<一个 href>
- 如何从一个 HREF 填充多个输入字段
- 将现有单选按钮更改为 <一个 href>
- 如何使用 JavaScript 单击一个 href 后编辑 3 个标签的值
- 返回值从 Javascript 到 HTML <一个 href> 标记
- 与号(&)在 DOM 中不转义会生成一个 href
- 使用php变量+javascript变量创建一个href-url
- <一个 href=#> 重定向到索引的链接..php
- 使文件输入成为一个href
- 带有javascript递增url的下一个/上一个href按钮
- 在 Echo 语句中插入一个 href
- 用jquery在一个href值的末尾添加
- 如何防止默认和禁用一个href
- 一个href click或onclick 2个动作(两个或更多函数)
- 如何循环遍历一个href's列表
- 如何通过jquery .html创建一个href,然后使用它的事件
- 向javascript代码中添加一个href类
- 选择一个href="#"打开父母李
- 如何使一个链接记住它的价值作为一个href之前转移到下一页中使用