首页 > 解决方案 > 在 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我的元素的属性发生更改时,我都会触发一个函数。

标签: javascripthtmljquery

解决方案


您可以使用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>


推荐阅读