我想在$("#address").change
函数中执行警报,但只有在使用按钮更改值时才需要执行此操作。
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$('button').click(function(){
$("#address").val("hi")
})
$("#address").change(function(){
alert("The text has been changed.");
});
});
</script>
</head>
<body>
<input type="text" id="address">
<button>Click</button>
</body>
</html>
答案 0 :(得分:7)
您可以在change
功能中触发click
事件:
$('button').click(function(){
$("#address").val("hi")
$("#address").change(); //or $("#address").trigger("change");
});
$("#address").change(function(){
alert("The text has been changed.");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="address" type="text">
<button>Change</button>
答案 1 :(得分:0)
Trigger更改事件如下:
$('button').click(function(){
$("#address").val("hi")
$("#address").trigger('change');
});
$("#address").change(function(){
alert("The text has been changed.");
});
答案 2 :(得分:0)
如果您希望#address上的警报仅在单击按钮时更改,而不是在手动更改#address值时更改:
var textChangedHandler = function() {
alert("The text has been changed.");
};
$('button').click(function(){
// Attach event handler for 'change' to #address
$("#address").bind("change", textChangedHandler);
// Update #address value
$("#address").val("hi");
// Trigger 'change'
$("#address").trigger('change');
// Remove event handler for 'change' from #address
$("#address").unbind("change", textChangedHandler);
});