javascript - 一旦有值使用 javascript 填充或在输入字段中使用键盘输入时检测
问题描述
我编写了这段代码,它检测是否productName
使用 javascript 在字段中填充了值,然后解析并自动填充输入字段quantity
。我的代码仅在productName
通过javascript代码填充字段并且在我使用时无法注册键盘输入时才有效onChange
我想在这两种情况下检测,即 javascript 和键盘,如何在这段代码中检测使用键盘?
const input = document.getElementById('productName');
const descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(input), 'value');
Object.defineProperty(input, 'value', {
set: function(t) {
console.log('Input value was changed programmatically');
descriptor.set.apply(this, arguments);
document.getElementById("quantity").value=t
},
get: function() {
return descriptor.get.apply(this);
}
});
var i=0;
function changeInput(){
/* console.log(document.getElementById('productName').value) */
document.getElementById("productName").value=i++;
}
<input type="text" id="productName" name="productName" placeholder="product name">
<input type="text" id="quantity" name="quantity" placeholder="quantity">
<button onclick="changeInput()">Change</button>
解决方案
由于我是 Javascript 的初学者,@epascarello 的评论帮助了我,这很容易绑定输入元素:
document.getElementById("productName").addEventListener("input",(event)=>{
document.getElementById("quantity").value= document.getElementById("productName").value;
})
推荐阅读
- java - 如果数据库中表的 ans 列为空,我想给出“编辑链接,即编辑”
- javascript - 如何在 React Native 中使用自定义警报?
- java - 如何使用 getter 和 setter 获取用户输入
- android - 为什么调用活动的 onActivityResult() 在被调用活动的 onCreate() 之前执行?
- c - 如何将 CSV 文件读入二维结构数组,每个元素都有一个确定字符(C、G、M)以排序到结构中?
- laravel - 并发连接 Apache 和 Laravel
- python - 带有 flow_from_directory val_acc 的 Keras VGG16 没有上升
- python - 读取最后打印的行并使用“if”语句将其删除
- matlab - how do I call an image that I have read on pushbutton1 to pushbutton4 on the matlab GUI?
- sql - 蜂巢日期转换问题