我知道我可以将值绑定到一个局部变量,比如selectedItem
,然后在on:change
中使用这个变量,如下所示:
<select bind:value={selectedItem} on:change={() => doSomething(selectedItem)}>
但在某些情况下,我更喜欢在on:change()
中直接使用value
,而不必首先定义中间selectedItem
变量。然而,我找不到这样做的方法,我缺少什么?
编辑:
我应该指出,列表中的项目是对象,因此使用event.target.value是不起作用的。我的问题似乎可以归结为:为什么value
可以用于绑定,但不能以某种方式用于on:change
?
通过on:change={(event) => doSth(event.target.value)}
访问该值将以字符串形式给出该值。虽然这基本上对基元没有问题,但值绑定的优点是Svelte保留了原始类型,并且可以使用对象作为值。这些不能通过event.target.value
访问-这将只提供[object Object]
REPL-
<script>
const options = [1,2,3]
let selectedOption = ''
let questions = [
{ id: 1, text: `Where did you go to school?` },
{ id: 2, text: `What is your mother's name?` },
{ id: 3, text: `What is another personal fact that an attacker could easily find with Google?` }
];
let selectedQuestion = ''
</script>
<select bind:value={selectedOption}
on:change={(event) => console.log(event.target.value, typeof event.target.value, selectedOption, typeof selectedOption)}
>
{#each options as option}
<option value={option}>
{option}
</option>
{/each}
</select>
<select bind:value={selectedQuestion}
on:change={(event) => console.log(event.target.value, selectedQuestion)}
>
{#each questions as question}
<option value={question}>
{question.text}
</option>
{/each}
</select>
您可以使用onChange参数来查找目标的值:
<select on:change={(e) => doSomething(e.target.value)}>
你可以在这里阅读更多关于文档的信息:HTMLElement更改事件