检测通过代码对输入所做的更改 [英] Detect changes made to input through code
问题描述
在页面的某个位置,我有一个按钮,单击该按钮可更改另一个输入的值.但是,我无法控制定义click事件(在客户的CDN上)的代码,因此我也没有去理会.我只是想在代码中输入的值发生更改时捕获事件.这是一个示例:
HTML
Somewhere in my page I have an button that when clicked changes the value of another input. However I don't have control over the code where the click event is defined (on a clients' CDN) and I didn't bother to look. I just want to capture the event when my inputs' value is change through the code. Here's an example:
HTML
<input type="text" id="myinput" />
<input type="button" id="theonechanging" value="Click Me" />
<br />
<p id="message"></p>
JS
var i = 0;
$("#theonechanging").click(function(e) {
// YOU CAN NOT CHANGE THIS FUNCTION
$("#myinput").val("changed via button " + i++);
});
$("#myinput").on("input change bind",function(e) {
$("#message").text("changed " + i++);
});
这里有一个小提琴,您可以在其中进行测试: http://jsfiddle.net/fourat05/t9x6uhoh/
Here's a fiddle where you can test the situation: http://jsfiddle.net/fourat05/t9x6uhoh/
谢谢您的帮助!
推荐答案
有一种非常骇人听闻的方法来实现此目的.
There's an incredibly hacky way to do this.
您要做的是用自己的实现替换jQuery.fn.val
函数,并从新的实现中调用旧的实现.这种技术是一种猴子修补.
What you do is replace the jQuery.fn.val
function with your own implementation, and call the old implementation from the new one. This technique is a kind of Monkey patching.
实现如下:
var i = 0;
$("#theonechanging").click(function(e) {
// YOU CAN NOT CHANGE THIS FUNCTION
$("#myinput").val("changed via button " + ++i);
});
var handleChanges = function(){
$("#message").text("changed " + i);
}
var oldval = jQuery.fn.val;
jQuery.fn.val = function(){
oldval.apply(this,arguments);
if(this.attr('id') === 'myinput'){ //and possibly add a check for changes
handleChanges();
}
}
$("#myinput").on("input change bind",function(e) {
i++;
handleChanges();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="text" id="myinput" />
<input type="button" id="theonechanging" value="Click Me" />
<br />
<p id="message"></p>
但是,我强烈建议您不要使用它,因为:
However, I strongly recommend against using it, because:
- 这改变了广泛使用的库的行为,从而为开发人员为同一页面生成代码提供了可能的陷阱
- 检测多个元素上的多个事件将很快变得复杂.
在实施此方法之前,请先了解其副作用.
Please understand the side effects of this method before implementing it.
这篇关于检测通过代码对输入所做的更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!