html - 在迭代中使用 div 元素的 onclick 事件获取数据
问题描述
我正在尝试详细显示单击的记录,我需要为此单击 div 的键值。
我尝试使用 event.target.value,但它给了我 0 作为值。
HTML 代码
<div class="slds-scrollable_y" style="height:300px">
<template
for:each={contacts.data}
for:item="contact"
>
<div
class="slds-p-top_small"
key={contact.Id}
onclick={handleContactClick}
id={contact.Id}
>
<ul>
<li class="slds-item">
{contact.Name}
</li>
<li class="slds-item">
{contact.Phone}
</li>
</ul>
<div class="slds-p-top_small">
<hr>
</div>
</div>
</template>
</div>
Javascript 文件
import { LightningElement, track, wire } from 'lwc';
import searchContacts from '@salesforce/apex/ContactsListController.searchContacts'
export default class ContactList extends LightningElement {
@track searchTerm = ''
@track contacts
@track selectedContact = ''
@wire(searchContacts, { searchTerm: '$searchTerm' })
loadContacts(result) {
this.contacts = result
}
handleContactSearch(event){
//Debounce the method
window.clearTimeout(this.delayTimeout)
const searchTerm = event.target.value;
// eslint-disable-next-line @lwc/lwc/no-async-operation
this.delayTimeout = setTimeout(() => {
this.searchTerm = searchTerm
}, 300)
}
handleContactClick(event){
// eslint-disable-next-line no-console
console.log(event.target.value);
this.selectedContact = event.target.value;
}
checkIfEmpty(){
// eslint-disable-next-line eqeqeq
return this.selectedcontact == '';
}
}
我希望 event.target.value 提供联系人的 ID,但它返回 0。
解决方案
您应该尝试使用id
clicked <div>
:
handleContactClick(event){
// eslint-disable-next-line no-console
console.log(event.currentTarget.id);
this.selectedContact = event.currentTarget.id;
}
更新
根据评论将目标替换为 currentTarget
推荐阅读
- css - 如何在 Production Build Vue 上安排 CSS 顺序?
- amazon-web-services - 如何扩展 AWS 应用程序负载均衡器?
- android - 在 Android Studio 中构建并运行旧的 Android 项目
- python - 通过环境设置恢复 rcdefaults
- python - 优先考虑多个正则表达式模式
- python - 如何在 Python 的 Matplotlib 中绘制嵌套饼图?
- python - 在 Python 中为方法动态选择正确的参数
- java - 使用分隔符分隔模式
- ios - Media-soup ios客户端远程视频未显示
- python - Makefile:使用 -j 选项时目标的配方失败