我正在尝试制作一个简单的脚本来使用星空系统处理收视率。 我在按下星号的那一刻就停了下来,因为在删除一个事件监听器的同时,所有星号在单击一个星号后都应保持在原处。
你能告诉我我在做什么错吗?我怀疑removeEventListener不能正常工作; |
const drawStars = (node, starsNumber = 5, cssRef = "_star") => {
if (starsNumber < 1)
return false;
let star;
// classes to aply when star's filled or not
const starFilled = `fas fa-star ${cssRef}`;
const starContour = `far fa-star ${cssRef}`;
// drawing stars
for (let i = 1; i <= starsNumber; i++) {
star = document.createElement('i');
star.className = `${starContour} ${cssRef}`;
node.appendChild(star);
}
node = [...node.childNodes];
// putting listeners on every star
node.forEach((star, index) => {
// filling stars after hovering
const mouseOverStar = () => {
for (let i = 0; i < starsNumber; i++) {
if (i <= index)
node[i].className = starFilled;
else
node[i].className = starContour;
}
}
// cleaning stars when mouse is out and no star was clicked
const mouseOutStar = () => {
node.forEach(star => star.className = starContour);
}
// trying to remove event listeners from every star but with no effect
const clickOnStar = () => {
node.forEach(star => {
star.removeEventListener('mouseout', mouseOutStar);
star.removeEventListener('mouseover', mouseOverStar);
})
}
// applying listeners
star.addEventListener('mouseover', mouseOverStar);
star.addEventListener('mouseout', mouseOutStar);
star.addEventListener('click', clickOnStar);
});
}
// example of use
const starsContainer = document.querySelector('.stars');
drawStars(starsContainer);
.stars {
margin: 30px;
font-size: 30px;
color: rgb(231, 199, 19);
cursor: pointer;
}
<html>
<head>
<link href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" rel="stylesheet" />
</head>
<body>
<div class="stars"></div>
</body>
</html>
答案 0 :(得分:0)
尝试在mouseOverStar
函数之外定义事件处理程序mouseOutStar
,clickOnStar
和drawStars
。
您需要在addEventListener
和removeEventListener
中引用完全相同的处理程序,以使其正常工作。
选中https://www.jonportella.com/you-are-using-browser-events-wrong/