javascript - 在 JavaScript 中将事件侦听器添加到隐藏的输入类型
问题描述
我想将事件侦听器添加到隐藏的输入元素。
我试过了:
document.querySelector('#myDate').addEventListener('change', foo);
其中 foo 是我想在更改时调用的函数。
我知道jQuery默认情况下不会触发更改,并且我还查看了该网站的源代码,并且该网站没有使用.change()
或.trigger()
仅.val()
在他们尝试更新隐藏元素的值时使用。我还尝试了jQuery - Detect value change on hidden input field
中列出的不同方法,但这也无济于事。
我的 HTML 元素:
<input type="hidden" name="myDate" id="myDate" value="31-DEC-2017">
我还尝试为我的日历中的每个日期元素添加一个事件侦听器,这基本上是一个表格,每个日期都是一个 td 元素。但这也失败了。
编辑:
似乎你们中的大多数人都误解了我的最终目标,我很抱歉没有清楚地表达我想要做什么。我只是想为我的隐藏输入元素添加一个侦听器,以便每当value
我的元素的属性发生更改时,我都会触发一个函数。
解决方案
您可以使用Object.defineProperty
为 的value
属性定义 getter 和 setter,input
以便每次设置属性时都会收到通知。
var input = document.getElementById("myDate");
var value = input.value;
Object.defineProperty(input, "value", {
set(newValue) {
console.log("Value changed to", newValue);
value = newValue;
},
get(){
return value;
}
});
$('#changeValue').click(function(e){
$('#myDate').val($('#newValue').val());
});
<input type="hidden" name="myDate" id="myDate" value="31-DEC-2017">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<input id="newValue">
<button id="changeValue">Change Value!</button>
您也可以使用MutationObserver
.
var input = document.getElementById("myDate");
var observer = new MutationObserver(function(mutations, observer) {
if(mutations[0].attributeName == "value") {
$(input).change();
}
});
observer.observe(input, {
attributes: true
});
$(input).change(function(e){
console.log("Value changed to", $(this).val());
});
$('#changeValue').click(function(e){
$('#myDate').val($('#newValue').val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<input type="hidden" name="myDate" id="myDate" value="31-DEC-2017">
<input id="newValue">
<button id="changeValue">Change Value!</button>
推荐阅读
- bash - 如何逐行压缩标准输入和标准输出
- oracle - Cursor Select 语句 where 条件根据条件而变化
- grpc-java - grpc-java 双向流性能
- python - OpenMDAO 的 SimpleGADriver 中自动计算的位,具有整数值
- java - JMeter - 不支持的 major.minor 版本 51.0
- c# - 检查 c# 中至少一个文本框值是否不为空或零?
- android - 循环失败,不会增加数量,android studio
- c++ - POCO C++ 对象到 JSON 字符串序列化
- swift - Firebase 存储
- function - 定义八度函数