admin管理员组文章数量:1429064
I need to get a reference to every div created inside a each loop in svelte, then I'll use the reference to toggle css class of a certain div when the user clicks on previous div.
let contentOptions;
function handleClick(event) {
contentOptions.classList.toggle("close");
}
{#each items as item, i}
<div class="titleOption" on:click={handleClick}>
<img src="./assets/{item.icon}"/>
<span>{item.label}</span>
</div>
<div class="content close" bind:this={contentOptions}>Content Option {i}</div>
{/each}
Items array have three objects, and it always appears the last div with text "Content Option 2" despite clicking on another div.
is possible to bind each div separately?
I need to get a reference to every div created inside a each loop in svelte, then I'll use the reference to toggle css class of a certain div when the user clicks on previous div.
let contentOptions;
function handleClick(event) {
contentOptions.classList.toggle("close");
}
{#each items as item, i}
<div class="titleOption" on:click={handleClick}>
<img src="./assets/{item.icon}"/>
<span>{item.label}</span>
</div>
<div class="content close" bind:this={contentOptions}>Content Option {i}</div>
{/each}
Items array have three objects, and it always appears the last div with text "Content Option 2" despite clicking on another div.
is possible to bind each div separately?
Share Improve this question asked Jan 20, 2022 at 13:24 Toni BCNToni BCN 3925 silver badges18 bronze badges1 Answer
Reset to default 7You can solve this by making contentOptions
an array, bind with the index bind:this={contentOptions[i]}
and use the index inside the function to target the right reference > REPL
<script>
const items = [{label: 'item1'}, {label: 'item2'}]
let contentOptions = [];
function handleClick(index) {
contentOptions[index].classList.toggle("close");
}
</script>
{#each items as item, i}
<div class="titleOption" on:click={() => handleClick(i)}>
<span>{item.label}</span>
</div>
<div class="content close" bind:this={contentOptions[i]}>Content Option {i}</div>
{/each}
<style>
.close {
background: red;
}
</style>
This would be an alternative way without the need of the extra array and handling binding and index REPL
<script>
const items = [{label: 'item1'}, {label: 'item2'}]
function handleClick(event) {
event.currentTarget.nextElementSibling.classList.toggle('close')
}
</script>
{#each items as item, i}
<div class="titleOption" on:click={handleClick}>
<span>{item.label}</span>
</div>
<div class="content close">Content Option {i}</div>
{/each}
<style>
.close {
background: red;
}
</style>
本文标签: javascriptSvelte how to bind div inside each lop to obtain a reference using thisStack Overflow
版权声明:本文标题:javascript - Svelte how to bind div inside each lop to obtain a reference using this - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745516411a2661566.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论