javascript - 在Javascript中更改模板字符串中的复选框的三元代码
问题描述
我正在使用聚合物和发光元素。在渲染函数中,我有一个模板字符串,如下所示:
render() {
this.todoItem = JSON.parse(this.todoItem);
return html`
<li>
${this.todoItem.item} <button @click="${this.onRemove}">Remove</button>
<input
type="checkbox"
checked="${this.todoItem.done} ? 'true' : 'false'"
@click="${this.changeStatus}"
/>
</li>
`;
}
我知道这行不通,因为基于几个stackoverflow答案,您设置的任何checked
等于的值都会将其标记为已检查。
如果我这样做:
<input type="checkbox" ${this.todoItem.done} ? 'checked' : ''" @click="${this.changeStatus}"/>
我收到一个错误
TypeError:无法在“TreeWalker”上设置“currentNode”属性:提供的值不是类型
解决方案
遵循文档后,我找到了答案:我不得不使用html
https://lit-element.polymer-project.org/guide/templates。以下代码有效。
render() {
this.todoItem = JSON.parse(this.todoItem);
return html`
<li>
${this.todoItem.item} <button @click="${this.onRemove}">Remove</button>
${this.todoItem.done
? html`
<input type="checkbox" checked @click="${this.changeStatus}" />
`
: html`
<input type="checkbox" @click="${this.changeStatus}" />
`}
</li>
`;
}
更新
render() {
this.todoItem = JSON.parse(this.todoItem);
return html`
<li>
${this.todoItem.item} <button @click="${this.onRemove}">Remove</button>
${html`
<input type="checkbox" ?checked="${this.todoItem.done}" @click="${this.changeStatus}" />
`}
</li>
`;
}
更新 V2
render() {
this.todoItem = JSON.parse(this.todoItem);
return html`
<li>
${this.todoItem.item} <button @click="${this.onRemove}">Remove</button>
<input type="checkbox" ?checked="${this.todoItem.done}" @click="${this.changeStatus}" />
</li>
`;
}
推荐阅读
- javascript - 将未设置的属性设置为函数中的默认属性?
- assembly - 为什么一个由 Brainfuck 创建的程序在汇编编译器中崩溃?
- java - Spark SQL:在数组值上使用 collect_set?
- php - 如何将用户重定向到他们的特定子文件夹?
- ionic-framework - 我在 ionic 3 应用程序中显示媒体时遇到问题
- azure - 使用队列而不是主题和订阅有什么意义吗?
- javascript - Vuetify v-select 值不返回键
- python - 为什么在使用 Gmail API python 导入电子邮件时 mime 部分变为“0”?
- swift - NSPersistentDocument 和文件菜单项
- python - Pyomo:超出 Ipopt 最大迭代次数