gpt4 book ai didi

javascript - 如何使用 javascript 检测 textarea 值何时更改?

转载 作者:行者123 更新时间:2023-11-29 21:12:40 26 4
gpt4 key购买 nike

如何使用 javascript 检测 textarea 值何时更改?

将数据填入id="yyyy" 然后数据id="xxxx"也会改变,我如何alert when value in id="xxxx" 改变了吗?

https://jsfiddle.net/9b6h897d/10/

请不要编辑函数 checkid="yyyy" 中的代码

<textarea id="yyyy" onkeyup="check(this.value)"></textarea>
<textarea id="xxxx" onchange="check2(this.value)" readonly></textarea>

<script>
function check(value){
document.getElementById("xxxx").value = value;
}
function check2(value){
alert(value);
}
</script>

最佳答案

您可以重新定义 textarea 元素的 value 属性:

<html>
<head>
<script>
//Is not changable according to OP
function check(value){
document.getElementById('xxxx').value = value
};

//Is not changable according to OP
function check2(value){
alert(value)
};

window.onload = function(){
var tE = document.querySelector('#xxxx'); //The readonly textarea

//Redefine the value property for the textarea
tE._value = tE.value;
Object.defineProperty(tE, 'value', {
get: function(){return this._value},
set: function(v){
console.log(this.id, ' - the value changed to: ' + v)
this._value = v;
this.setAttribute('value', v) //Setting the attribute (browser stuff);
check2(v)
}
})
}
</script>
</head>

<body>
<textarea id = 'yyyy' onkeyup = 'check(this.value)'></textarea>
<textarea id = 'xxxx' onchange = 'check2(this.value)' readonly></textarea>
</body>
</html>

控制台日志(): https://jsfiddle.net/mu7o1sxq/

警报(): https://jsfiddle.net/mu7o1sxq/2/

关于javascript - 如何使用 javascript 检测 textarea 值何时更改?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41011933/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com