我正面临着处理input
字段的更改事件的问题。因为我正在通过另一个脚本更改输入字段的文本。因此,我无法捕捉到这一事件。
看,这里我有两个按钮-
和+
当我点击 - / +然后在文本框内插入一些值。它是一个数值,我通过包含和减少手动添加增量和减量1.无论如何,因为我在文本框内的文本正在改变,但是我无法在jQuery
中捕获事件
我的代码如下
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<button>-</button><input type="text" id="abc" /><button>+</button>
并且我的jQuery函数都没有捕获事件。
$("#abc").change(function(){
alert();
});
$("#abc").click(function(){
alert();
});
因为我已经通过另一个jQuery
帮助器添加了文本。那么如何才能捕获文本更改事件。我不想写下增量和减量函数内的代码。我想保持代码完好无损。那么有什么办法可以轻松解决这个问题吗?提前致谢。
更新 这是增量和减量的更新代码
var btn = $(this),
oldValue = $('#abc').val().trim(),
newVal = 0;
if (btn.attr('data-dir') == 'up') {
newVal = parseInt(oldValue) + 1;
} else {
newVal = parseInt(oldValue) - 1;
}
$('#abc').val(newVal);
答案 0 :(得分:1)
您需要.trigger(event)
事件,当用户与元素交互时会触发事件。
$("#abc").change(function() {
console.log('changed', this.value);
});
$("button").click(function() {
var btn = $(this),
oldValue = $('#abc').val().trim(),
newVal = 0;
if (oldValue != '') {
if (btn.attr('data-dir') == 'up') {
newVal = parseInt(oldValue, 10) + 1;
} else {
newVal = parseInt(oldValue, 10) - 1;
}
}
$('#abc').val(newVal).trigger('change');
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<button data-dir="down">-</button><input type="text" id="abc" /><button data-dir="up">+</button>
&#13;
答案 1 :(得分:1)
由于更改输入的其他脚本也使用jquery,因此最可靠的方法可能是在输入值更新后手动触发更改事件。
$('.counter').val(oldValue + 1).trigger('change');