javascript - 如何在一个函数中为不同的按钮添加多个事件监听器?
问题描述
const nbaLoads = () => {
fetch('nba.json')
.then(res => res.json())
.then(data => {
let output = '';
data.forEach(s => {
if(s.year === parseInt(select.value)){
output += `
<img src="" width= 100px; height=100px>
<h4>CHAMPIONS: ${s.champion}</h4>
`
} if(s.year === parseInt(select.value)){
output += `
<img src="" width= 100px; height=100px>
<h4>RUNNER UP: ${s.runnerUp}</h4>
`
}
});
document.querySelector('#output').innerHTML = output;
})
};
champion.addEventListener('click', nbaLoads);
runnerUp.addEventListener('click', nbaLoads);
如果我点击冠军按钮,我的结果是冠军和亚军。如果我点击亚军按钮,结果是一样的,如何更改?当我点击冠军按钮时,我想看到冠军,当我点击亚军时,我想看到亚军。
提前致谢
解决方案
您在两个按钮单击时调用相同的函数。您需要提供一个参数来指示您应该设置什么类型的信息innerHTML
,或者创建两个不同的函数。
第一个解决方案:
const nbaLoads = (type) => {
fetch('nba.json')
.then(res => res.json())
.then(data => {
let output = '';
data.forEach(s => {
if(s.year === parseInt(select.value) && type == "champions"){
output += `
<img src="" width= 100px; height=100px>
<h4>CHAMPIONS: ${s.champion}</h4>
`
} if(s.year === parseInt(select.value) && type == "runnerUp"){
output += `
<img src="" width= 100px; height=100px>
<h4>RUNNER UP: ${s.runnerUp}</h4>
`
}
});
document.querySelector('#output').innerHTML = output;
})
};
champion.addEventListener('click', () => nbaLoads("champions"));
runnerUp.addEventListener('click', () => nbaLoads("runnerUp"));
第二种解决方案:
const nbaLoads = () =>
fetch('nba.json')
.then(res => res.json());
const loadChampion = () =>
nbaLoads()
.then(data => {
let output = '';
data.forEach(s => {
if (s.year === parseInt(select.value)) {
output += `
<img src="" width= 100px; height=100px>
<h4>CHAMPIONS: ${s.champion}</h4>
`;
}
});
document.querySelector('#output').innerHTML = output;
});
const loadRunnerUp = () =>
nbaLoads()
.then(data => {
let output = '';
data.forEach(s => {
if (s.year === parseInt(select.value)) {
output += `
<img src="" width= 100px; height=100px>
<h4>RUNNER UP: ${s.runnerUp}</h4>
`;
}
document.querySelector('#output').innerHTML = output;
});
});
champion.addEventListener('click', loadChampion);
runnerUp.addEventListener('click', loadRunnerUp);
推荐阅读
- python - 使用 Boto3 创建胶水表
- javascript - 数组推送和弹出操作——它们是原子的吗?
- scala - 在 Databricks 笔记本中为 spark.sql 创建一个函数
- nfsclient - 如何使用 libnfs-python 为上下文完整句柄创建 NFS 上下文
- javascript - 如果选中其中一个单选按钮,如何更改两段中的文本?JS
- java - 从 Java AWS lambda API 响应中的字节数组返回图像
- c - 我不小心在命令中写了错误的文件名并且文件已删除
- r - ggplot 只有黑点,没有颜色
- ios - 了解钥匙串项目的访问控制设置`.userPresence`
- php - php goutte web scraper 不时给出不同的结果