change()当值设置时,事件处理程序中的逻辑不会运行val(),但它会在用户使用鼠标选择值时运行.为什么是这样?
<select id="single">
<option>Single</option>
<option>Single2</option>
</select>
<script>
$(function() {
$(":input#single").change(function() {
/* Logic here does not execute when val() is used */
});
});
$("#single").val("Single2");
</script>
Run Code Online (Sandbox Code Playgroud) 我的目标是观察输入值并在其值以编程方式更改时触发处理程序.我只需要它用于现代浏览器.
我尝试了很多组合使用defineProperty,这是我最新的迭代:
var myInput=document.getElementById("myInput");
Object.defineProperty(myInput,"value",{
get:function(){
return this.getAttribute("value");
},
set:function(val){
console.log("set");
// handle value change here
this.setAttribute("value",val);
}
});
myInput.value="new value"; // should trigger console.log and handler
Run Code Online (Sandbox Code Playgroud)
这似乎做了我的预期,但感觉就像一个黑客,因为我重写现有的价值属性和玩value(属性和属性)的双重身份.它还打破了change似乎不喜欢修改属性的事件.
我的其他尝试:
watch和observepolyfill,但它们打破输入值属性什么是获得相同结果的正确方法?
现场演示:http://jsfiddle.net/L7Emx/4/
[编辑]澄清一下:我的代码正在观看一个输入元素,其他应用程序可以推送更新(例如,由于ajax调用,或者由于其他字段的更改).我无法控制其他应用程序如何推送更新,我只是一个观察者.
[编辑2]为了澄清"现代浏览器"的含义,我对能够在IE 11和Chrome 30上运行的解决方案感到非常满意.
[更新]根据接受的答案更新了演示:http://jsfiddle.net/L7Emx/10/
@ mohit-jain建议的技巧是为用户交互添加第二个输入.
我想检测输入字段中文本/值的变化.所以我读了很多例子并尝试下面的代码.但它不起作用.这是小提琴预览.即使我用js代码改变值我想要检测到这些变化.
HTML
<input type="text" id="exNumber"/>
Run Code Online (Sandbox Code Playgroud)
JavaScript的
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
// console.log('Mutation type: ' + mutation.type);
if ( mutation.type == 'childList' ) {
if (mutation.addedNodes.length >= 1) {
if (mutation.addedNodes[0].nodeName != '#text') {
// console.log('Added ' + mutation.addedNodes[0].tagName + ' tag.');
}
}
else if (mutation.removedNodes.length >= 1) {
// console.log('Removed ' + mutation.removedNodes[0].tagName + ' tag.')
}
}
if (mutation.type == 'attributes') {
console.log('Modified ' + mutation.attributeName + ' attribute.')
}
});
}); …Run Code Online (Sandbox Code Playgroud)