如果 jQuery 设置了值,如何触发 'change' 事件?



如果jQuery设置该按钮的值,如何触发"change"事件?可能吗?

代码片段附在下面:

$(".first").change(function() {
alert('something');
})
$(".button").click(function() {
$(".first").val('Button Value');
})
<!DOCTYPE html>
<html>
<head>
<title>Change</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<input type="text" name="" class="first">
<input type="button" name="" class="button" value="Change">
</body>
</html>

答案就在问题中!!使用.trigger()

$(".first").change(function(){
alert('something');
})
$(".button").click(function(){
$(".first").val('Button Value').trigger("change");
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="" class="first"> 
<input type="button" name="" class="button" value="Change">

它不会调用更改事件,也许你可以像这样手动调用它。

$(".first").on('change',function(){
alert($(".first").val());
})
$(".button").click(function(){
$(".first").val('Button Value');
$(".first").change();
})

更新:

使用元素值更改时引发的oninput

$(".first").on('input', function(){
alert('something');
})

这里是一个简单的例子

$(".first").on('input', function(){
alert('something$(".first").on('input', function(){
alert('something');
})');
})

我猜您想在单击按钮时在页面上弹出警报,即当用户向表单提交一些数据而不是在确切时刻发出警报时,您希望在用户单击按钮时弹出警报。因为这就是我从你的问题中理解的。也许要做到这一点,我们所能做的就是:

$(".button").click(function(){
alert("something");
$(".first").css("outline", "1px solid #3366BB";
});

看看这是否有帮助。

最新更新