如何在Svelte复选框中使用Checked HTML属性?

huangapple go评论61阅读模式
英文:

How to use Checked HTML Attribute in Svelte Checkbox?

问题

我正在使用Laravel和Svelte制作一个简单的CRUD。我有一个复选框字段,并且想要通过给予 "checked" 属性来默认选中它。问题是,如果我尝试这样做,Svelte会抛出错误,说 "属性需要是唯一的":

```html
<input type="checkbox" class="form-check-input" id="remember" bind:checked={$form.remember} checked>

在这种情况下,如何使用HTML属性 "checked"?


<details>
<summary>英文:</summary>

I&#39;m making a simple CRUD in Laravel and Svelte. I have one checkbox field and I would like to give &quot;checked&quot; attribute so it&#39;s checked by default. The problem is that Svelte throws error if I try to do so saying &quot;Attribute needs to be unique&quot;:


<input type="checkbox" class="form-check-input" id="remember" bind:checked={$form.remember} checked>


How do I use checked HTML attribute in this case?

</details>


# 答案1
**得分**: 0

如果这是所期望的默认设置,我只需相应地初始化`form`存储。

另一种选择可能是使用一个动作,例如:

```js
function check(node) { node.setAttribute('checked', '') }
<input ... use:check />

不建议这样做,因为它与现有的绑定冲突。

英文:

If that is the desired default, I would just initialize the form store accordingly.

An alternative might be using an action, e.g.

function check(node) { node.setAttribute(&#39;checked&#39;, &#39;&#39;) }
&lt;input ... use:check /&gt;

Would not recommend that, it fights the existing binding.

huangapple
  • 本文由 发表于 2023年6月5日 16:23:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/76404639.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定