【问题标题】:How to set checked attribute to radio in litelement如何在litelement中将checked属性设置为radio
【发布时间】:2019-04-26 11:22:02
【问题描述】:

我想知道如何使用 litelement 将选中的设置为单选按钮。 我有一个对象,并且为每个对象选项创建单选按钮。

例如,对于id=SG,创建了两个单选按钮, 如果没有选中,将银行设置为默认选中 否则将相应的选定单选值设置为选中。

我被 litelement 卡住了。

const obj= [{
    id: "SG",
    options: ["bank", "credit"]
  },
  {
    id: "TH",
    options: ["bank"]
  }
];
render(){
  ${obj.map((e)=>{
return html`
         <form>
            ${obj.options.map((option_value)=>{
                   return html`
                       <input class="form-check-input"  name="sending-${option_value}" type="radio" id="provider-send-${option_value}" value=${option_value} ?checked=${option_value=="bank"} > // not working
                         <label class="form-check-label">
                                ${option_value}
                         </label><br>
             `})}
          </form>
   })`;

}
Expected Output:
Set checked to corresponding radio selected
If no checked, set bank as default checked

【问题讨论】:

  • 那是你的实际代码吗?因为您似乎在?checked={option_value=="bank"} 中缺少$
  • @dork,感谢回复,实际代码中有$,更新代码,sry

标签: javascript jquery polymer lit-element lit-html


【解决方案1】:

如果选项是bank,这会将checked属性设置为true:

import { LitElement, html } from 'lit-element';

class TestElement extends LitElement {
  static get properties() {
    return {
      countries: {
        type: Array,
      },
    };
  }

  constructor() {
    super();
    this.countries = [
      {
        id: 'SG',
        options: ['bank', 'credit'],
      },
      {
        id: 'TH',
        options: ['bank'],
      },
      {
        id: 'MY',
        options: ['credit'],
      }
    ];
  }

  render() {
    return html`
      ${this.countries.map(country => html`
        <fieldset>
          <legend>${country.id}</legend>
          <form>
            ${country.options.map(option => html`
              <input
                id="provider-send-${option}"
                name="sending-${country.id}"
                type="radio"
                class="form-check-input"
                value="${option}"
                ?checked=${option === 'bank'}
              >
              <label class="form-check-label">${option}</label>
              <br>
            `)}
          </form>
        </fieldset>
      `)}
    `;
  }
}

customElements.define('test-element', TestElement);

看起来您只是错过了映射实际的 obj(我的 sn-p 中的 country)。

此外,为了更改所选电台,name 对于组中的所有电台应相同。您的代码为每个收音机设置了不同的名称。

【讨论】:

  • 感谢您的回复,但是如果单选选项是 credit is checked 并且会在单选中显示 bank and credit checked 会怎样
  • 对不起,什么?你能改写你的问题吗?
  • ?checked=${option === 'bank'} 这会检查默认银行选项,如果用户选择 credit 选项和单选按钮将同时显示 bank and credit option checked 右侧
  • 那么基本上表现得像一个普通的广播组吗?然后您应该更改无线电组的名称,而不是将名称设置为sending-${option}sending-${country.id} 会更适合这个。
  • 如果我也改变了,` ` 不工作
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-30
  • 1970-01-01
  • 1970-01-01
  • 2013-04-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多