Skip to main content
Svelte基础
介绍
响应
属性Props
逻辑表达式
事件
绑定
Classes和样式
动作Actions
转场
Svelte高阶
响应式进阶
内容复用
动画
高级绑定
高级转场
上下文API
特殊元素
脚本模块
接下来
SvelteKit基础
介绍
路由
加载数据
Headers和cookies
Shared modules
Forms
API routes
$app/state
Errors and redirects
Advanced SvelteKit
Hooks
Page options
Link options
Advanced routing
Advanced loading
Environment variables
Conclusion

小主,又一个新的指令bind:group。 当需要把多个单选框或复选框组合起来使用时可以用这个指令。绑定到相同组的单选框互相排它也就是同时只会有个单选框被选中, 如果是复选框绑定的值就是包含所有选中的复选框值的数组。 快动手试下吧,给单选框添加上bind:group={scoops}

If you have multiple type="radio" or type="checkbox" inputs relating to the same value, you can use bind:group along with the value attribute. Radio inputs in the same group are mutually exclusive; checkbox inputs in the same group form an array of selected values. Add bind:group={scoops} to the radio inputs...

App
<input
	type="radio"
	name="scoops"
	value={number}
	bind:group={scoops}
/>

再给复选框添加上bind:group={flavours}

...and bind:group={flavours} to the checkbox inputs:

App
<input
	type="checkbox"
	name="flavours"
	value={flavour}
	bind:group={flavours}
/>

Edit this page on GitHub

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<script>
	let scoops = $state(1);
	let flavours = $state([]);
 
	const formatter = new Intl.ListFormat('en', { style: 'long', type: 'conjunction' });
</script>
 
<h2>Size</h2>
 
{#each [1, 2, 3] as number}
	<label>
		<input
			type="radio"
			name="scoops"
			value={number}
		/>
 
		{number} {number === 1 ? 'scoop' : 'scoops'}
	</label>
{/each}
 
<h2>Flavours</h2>
 
{#each ['cookies and cream', 'mint choc chip', 'raspberry ripple'] as flavour}
	<label>
		<input
			type="checkbox"
			name="flavours"
			value={flavour}
		/>
 
		{flavour}
	</label>
{/each}
 
{#if flavours.length === 0}
	<p>Please select at least one flavour</p>
{:else if flavours.length > scoops}
	<p>Can't order more flavours than scoops!</p>
{:else}
	<p>
		You ordered {scoops} {scoops === 1 ? 'scoop' : 'scoops'}
		of {formatter.format(flavours)}
	</p>
{/if}