我确信这很简单,但是我阅读的所有内容都声称更改prop
或attr
值不会执行更改侦听器。就我而言。
$(document).on('keyup change', '.fire', function(e){
console.log("submit");
$(".editQuoteForm :input:not([type=hidden])").prop("disabled", true);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="editQuoteForm">
<input type="text" class="fire">
</form>
此侦听器两次向控制台输出“提交”。当我删除禁用所有输入字段的代码行时,它会按预期工作。如何防止禁用字段的代码再次触发事件?
先谢谢了。
答案 0 :(得分:1)
一种解决方案是在发出下一条语句之前检查目标输入的禁用状态。
在通过设置属性disabled
触发焦点丢失时,会触发change
事件。
$(document).on('keyup change', '.fire', function(e){
if (e.target.disabled) return false;
console.log("submit");
$(".editQuoteForm :input:not([type=hidden])").prop("disabled", true);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="editQuoteForm">
<input type="text" class="fire">
</form>
答案 1 :(得分:1)
为什么不只检查事件源?如果是disabled
,则什么也不做。
$(document).on('keyup change', '.fire', function(e){
// Only run the rest of the code if the source of the event
// wasn't a field that is now disabled.
if(!e.target.disabled){
console.log("submit");
$(".editQuoteForm :input:not([type=hidden])").prop("disabled", true);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="editQuoteForm">
<input type="text" class="fire">
<input type="text" class="fire">
<input type="text" class="fire">
<input type="text" class="fire">
<input type="text" class="fire">
<input type="text" class="fire">
</form>
答案 2 :(得分:0)
您的代码触发两次,因为您听键盘输入并进行更改。 首先触发Keyup事件,然后再进行更改。
您为什么需要更改?如果keyup已经完成了您想要的操作。 :)
如果您一次需要两个事件。您可以通过这种方式来防止多次触发。
$(document).on('keyup change', '.fire', function (e) {
if ($(".editQuoteForm :input:not([type=hidden])").prop("disabled") == false) {
console.log("submit");
$(".editQuoteForm :input:not([type=hidden])").prop("disabled", true);
// after process finish
$(".editQuoteForm :input:not([type=hidden])").prop("disabled", false);
}
});
答案 3 :(得分:0)
我现在已经重现了您的问题,这是由您的事件处理程序引起的。 protocol Animations {
func wiggle()
}
extension Animations {
func wiggle() {
let position = "position"
let wiggleAnimation = CABasicAnimation(keyPath: position)
wiggleAnimation.duration = 0.05
wiggleAnimation.repeatCount = 5
wiggleAnimation.autoreverses = true
wiggleAnimation.fromValue = CGPoint(x: self.center.x - 4.0, y: self.center.y)
wiggleAnimation.toValue = CGPoint(x: self.center.x + 4.0, y: self.center.y)
layer.add(wiggleAnimation, forKey: position)
}
}
extension UIButton: Animations {}
extension UITextField: Animations {}
和change
在每个输入上均被触发。您必须考虑一下并选择适当的事件,否则您可以基于keyup
分离逻辑,但是我不建议您这样做。