我想使用 jquery 中的按键事件将文本放入 textarea 输入元素中。我知道可以简单地使用 .val()
或 .html()
函数来完成,但我想使用键事件来放置文本是有原因的。以下是我的代码:
<!DOCTYPE html>
<html>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<p>In this example, the text field gets focus immediately after the document window has been loaded.</p>
<textarea id="myText"> </textarea>
<script>
$(function() {
document.getElementById("myText").focus();
$('#myText').focus().trigger({ type : 'keypress', which : 65 });
$('#myText').trigger(jQuery.Event('keypress', { keyCode: 65 }));
});
</script>
</body>
</html>
我用 google 搜索了一下,发现有两种不同的方法可以使用 jquery 触发事件。我尝试了两者,但似乎都不起作用。
最佳答案
看起来您的按键事件正在被触发,但由于它只是一个事件,我不相信它实际上会将您的值输入到该字段中。如果您期望您拥有的其他代码在按键事件上发生某些事情,那么还有其他问题。
如果您使用 this fiddle 进行演示您将看到按键事件触发。
尝试使用下面的代码来使用新的按键值更改输入字段的值:
$(function() {
$('#myText').trigger(jQuery.Event('keypress', { keyCode: 65 })).val($("#myText")
.val() + String.fromCharCode(65));
});
关于javascript - 使用按键事件和 jquery 将文本放入输入元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42148644/