我正在编写一个函数检测$("input[name='AAA']")
输入是否已更改,如果输入已更改,单击应用按钮将弹出警报,但我的警报消息弹出三次,如何避免?
HTML部分:
<ul class="form">
<li>
<span class="clumn1">Name:</span>
<span class="clumn2">
<input class="text" type="text" name="AAA">
</span>
</li>
<li>
<span class="clumn1">Address:</span>
<span class="clumn2">
<input class="text" type="text" name="BBB">
</span>
</li>
<li>
<span class="clumn1">Date:</span>
<span class="clumn2">
<input class="text" type="text" name="CCC">
</span>
</li>
</ul>
<a class="submitBtn" onclick="apply()" href="#">Apply</a>
jQuery部分:
$(document).ready(function () {
$("input[name='AAA']").each(function() {
var stuff = $(this);
stuff.data('oldValue', stuff.val());
stuff.bind("input", function(event){
if (stuff.data('oldValue') != stuff.val()) {
$(".submitBtn").on("click", function () {
alert("Your changed name is:" + stuff.val())
});
}
});
});
});
答案 0 :(得分:0)
每次click
值更改时,您都会为该按钮绑定input[name='AAA']
事件。
您应该注册click
一次,并在事件处理程序内部比较旧输入值和新输入值:
var stuff = $("input[name='AAA']");
var stuff_val = stuff.val();
$(".submitBtn").on("click", function () {
if(stuff_val !== stuff.val()){
stuff_val = stuff.val();
alert("Your changed name is:" + stuff_val)
}
});
var stuff = $("input[name='AAA']");
var stuff_val = stuff.val();
$(".submitBtn").on("click", function () {
if(stuff_val !== stuff.val()){
stuff_val = stuff.val();
alert("Your changed name is: " + stuff.val());
}
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="form">
<li>
<span class="clumn1">Name:</span>
<span class="clumn2">
<input class="text" type="text" name="AAA">
</span>
</li>
<li>
<span class="clumn1">Address:</span>
<span class="clumn2">
<input class="text" type="text" name="BBB">
</span>
</li>
<li>
<span class="clumn1">Date:</span>
<span class="clumn2">
<input class="text" type="text" name="CCC">
</span>
</li>
</ul>
<a class="submitBtn" href="#">Apply</a>
&#13;