如何解决如何添加在粘贴后而不是之前对状态生效的EventListener?
示例:
<!DOCTYPE html>
<html>
<body>
<input type="text" id="myText" value="some text">
<button id='coolButton' onclick="coolFunction()">Click me</button>
<br><br>
<span>Entered:</span>
<span id="enteredBox"></span>
<script>
//display whatever is in the textbox in a text span below it
function coolFunction() {
word = document.getElementById("myText").value;
document.getElementById("enteredBox").innerHTML = word;
}
//trigger coolFunction() whenever something is pasted into the text box
document.getElementById('myText').addEventListener('paste',() => {
document.getElementById("coolButton").click();
});
</script>
</body>
</html>
当我单击“单击我”按钮时,文本框中当前显示的内容将正确显示在其下方。 当用户粘贴到框中时,我希望这种相同的行为自动发生。因此,我在文本框中添加了一个事件监听器,以监听粘贴。
但是,此粘贴侦听器中的代码适用于粘贴之前文本框中的内容。也就是说,如果文本框中有“ a”,并且用户将“ b”粘贴到框中,则下面只会显示“ a”(而不是“ ab”)。
如何使事件侦听器的代码在粘贴完成后生效?
我已经尝试过诸如强制其等待几秒钟或在单独的元素中显示等操作,但是粘贴功能代码始终读取粘贴之前而不是之后的框中内容。
解决方法
如何使事件侦听器的代码在粘贴完成后生效?
您可以使用.getData():
DataTransfer.getData()方法检索拖动数据(作为DOMString) 用于指定的类型。如果拖动操作不包含数据, 此方法返回一个空字符串。
要获取剪贴板数据,您需要按照documentation使用event参数到粘贴事件处理程序中。
摘要:
function coolFunction() {
word = document.getElementById("myText").value;
document.getElementById("enteredBox").innerHTML = word;
}
document.getElementById('myText').addEventListener('paste',function(e) {
// get the data from the clipboard.....
var txt = e.clipboardData.getData('text');
// use the data
document.getElementById("enteredBox").innerHTML = txt;
});
<input type="text" id="myText" value="some text">
<button id='coolButton' onclick="coolFunction()">Click me</button>
<br><br>
<span>Entered:</span>
<span id="enteredBox"></span>
或者,如果需要在粘贴操作完成后获取数据,则可以使用.setTimeout()来延迟click事件。在这种情况下,您的代码:
document.getElementById("coolButton").click();
成为:
setTimeout(() => document.getElementById("coolButton").click(),10)
摘要:
//display whatever is in the textbox in a text span below it
function coolFunction() {
word = document.getElementById("myText").value;
document.getElementById("enteredBox").innerHTML = word;
}
//trigger coolFunction() whenever something is pasted into the text box
document.getElementById('myText').addEventListener('paste',(e) =>
setTimeout(() => document.getElementById("coolButton").click(),10)
);
<input type="text" id="myText" value="some text">
<button id='coolButton' onclick="coolFunction()">Click me</button>
<br><br>
<span>Entered:</span>
<span id="enteredBox"></span>
最后一种解决方案可以完全避免使用按钮,它可以基于input event。
摘要:
document.getElementById('myText').addEventListener('input',function(e) {
word = document.getElementById("myText").value;
document.getElementById("enteredBox").innerHTML = word;
});
<input type="text" id="myText" value="some text">
<br><br>
<span>Entered:</span>
<span id="enteredBox"/>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。