Javascript 当dom被触发时,我如何构建一个事件处理函数来处理一个'event'对象
因此,我有一个个人的Javascript 当dom被触发时,我如何构建一个事件处理函数来处理一个'event'对象,javascript,html,Javascript,Html,因此,我有一个个人的prop和值的用户详细信息列表,例如height是道具,169cm是值 displaySelectedUser应该在触发DOM事件时接收事件对象,并在powerupTheUI中设置为更改事件侦听器。我已经设置了getSelectedUser,它根据用户的ID查找用户。我使用Object.keys()方法获取用户的属性集合 现在,在这个displaySelectedUser函数中,我应该使用array.forEach函数迭代属性,并在UI中显示属性。例如,像Age这样的给定属性
prop
和值的用户详细信息列表,例如height
是道具,169cm
是值
displaySelectedUser
应该在触发DOM事件时接收事件对象,并在powerupTheUI
中设置为更改事件侦听器。我已经设置了getSelectedUser
,它根据用户的ID查找用户。我使用Object.keys()方法获取用户的属性集合
现在,在这个displaySelectedUser
函数中,我应该使用array.forEach函数迭代属性,并在UI中显示属性。例如,像Age
这样的给定属性具有相应的span
元素,该元素具有数据年龄值属性。建议我使用ES6模板字符串来构建针对该属性的span
的查询选择器,然后使用它查询DOM。我需要确保只有在DOM查询成功时才更新UI
js
html
年龄:
23年
高度:
169厘米
重量:
68公斤
性别:
女性
国家:
加纳
如果我正确理解了您的问题,那么您可以通过构造查询字符串以匹配与该属性对应的
,然后通过document.querySelector()
方法选择该元素来更新所选用户属性值的显示,在您的情况下,该方法是:
document.querySelector(`.details span[data-${ property }-value]`)
一旦获取了用户属性的
元素,您就可以使用所选用户对象中该键的值更新其innerText
:
const displaySelectedUser = (event) => {
const { target } = event;
const user = getSelectedUser(target.value);
const properties = Object.keys(user);
/* Iterate each property of the user */
for(const property of properties) {
/* Query the document for a span element with the data attribute
corresponding to this property */
const valueSpan = document
.querySelector(`.details span[data-${ property }-value]`)
/* If span element found, update it's text with the value of
this user property */
if(valueSpan) {
valueSpan.innerText = user[property]
}
}
};
希望有帮助:-)
document.querySelector(`.details span[data-${ property }-value]`)
const displaySelectedUser = (event) => {
const { target } = event;
const user = getSelectedUser(target.value);
const properties = Object.keys(user);
/* Iterate each property of the user */
for(const property of properties) {
/* Query the document for a span element with the data attribute
corresponding to this property */
const valueSpan = document
.querySelector(`.details span[data-${ property }-value]`)
/* If span element found, update it's text with the value of
this user property */
if(valueSpan) {
valueSpan.innerText = user[property]
}
}
};