【问题标题】:How to display select options on alpinejs如何在 alpinejs 上显示选择选项
【发布时间】:2021-08-23 04:05:13
【问题描述】:

所以我正在使用 alpinejs,我想做一个“选择”,其中选项来自返回节点数组的 alpinejs x-data。我知道如何在 vanilla js 中做到这一点,您只需要创建一个循环,然后将这些元素附加到父元素。但是不知道如何在 alpine 中执行此操作,因为我尝试了不同的选项,但没有一个有效。

<div x-data="{ options: $el.querySelectorAll('.m-tab__title') }">
 <select class="w-full md:hidden">
        <template x-for="option in options">
            <option x-html="option"></option>
        </template>
 </select>...

这只是在选择中不显示任何内容,而是显示 [object HTMLDivElement]。

 <div x-data="{ options: $el.querySelectorAll('.m-tab__title') }">
     <select class="w-full md:hidden">
            <template x-for="option in options">
                <option x-text="option.innerText"></option>
            </template>
     </select>...

虽然只显示每个选项的内部文本,但甚至不显示在正确的选择内。

我可以将每个选项显示为选择选项吗?

谢谢!

【问题讨论】:

    标签: javascript dom tailwind-css dom-manipulation alpine.js


    【解决方案1】:

    您确定您的选项数组包含有效数据吗?

    如果你不确定你总是可以将x-init="console.log(options);" 添加到你的“x-data div”中

    我在这里做了一个简单的例子: https://codepen.io/outoforbit/pen/JjWaJKN

    <div x-data="{ selectedOption: 'option1', 
             options: [ 
                'option1',
                'option2', 
                'option3'
             ]}">
    <div class="w-80 flex pr-3">
        <p class="w-1/2">Select option:</p>
        <div class="w-1/2 inline-block relative">
            <select name="my_option" x-model="selectedOption" class="">
                <template x-for="option in options" :key="option">
                    <option :value="option" x-text="option"></option>
                </template>
            </select>
        </div>
    </div>
    
    选择选项:

    【讨论】:

      猜你喜欢
      • 2021-11-07
      • 2017-06-28
      • 2020-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-29
      相关资源
      最近更新 更多