Element:input 事件

当一个 input select 或 textarea 元素的 value 被修改时,会触发 input 事件。

事件的 target 为当前正在编辑的宿主。

每当元素的 value 改变,input 事件都会被触发。这与 change 事件不同。
change 事件仅当 value 被提交时触发,如按回车键,从一个 options 列表中选择一个值等。

示例:

<input placeholder="输入一些文本" name="name" />
<p id="values"></p>

<script>
const input = document.querySelector("input");
const log = document.getElementById("values");

input.addEventListener("input", updateValue);

function updateValue(e) {
  log.textContent = e.target.value;
}
</script>

对于input, 在Leptos中强调了 value attribute 和 value property 的区别。许多前端框架会混淆这两者。
https://book.leptos.dev/view/05_forms.html

attribute用来设置初始值,而property 则是设置当前值。就是当用户在 input界面上输入过之后,只能用 property来修改

打开浏览器的 about:blank 页面, 用 Ctrl + Shift + I 调出 调试界面,在 控制台里 依次 输入下面四句(输入完一句,看一下效果)

const el = document.createElement("input");
document.body.appendChild(el);

el.setAttribute("value", "test"); el.setAttribute("value", "another
test");

页面最后会出现一个 输入框
在 input框中输入几个字符,或者删除几个字符。

el.setAttribute("value", "one more time?");

再用 setAttribute 就无法改变 input的内容了,只能用prop

el.value = "But this works";

标签: none

添加新评论