我正在尝试为 HTML 页面实现一个 JavaScript 函数,该函数只需在鼠标按下时显示文本。我想多次应用此功能,因此不想为每个事件创建一个函数。
下面的代码工作正常...
function showSkillInfo() {
if (skill1Info.style.display === 'none') {
skill1Info.style.display = 'grid';
} else {
skill1Info.style.display = 'none';
};
};
skill1.onmousedown = showSkillInfo;
但是这块代码好像没有任何反应……
function showSkillInfo2(skill) {
if (skill.style.display === 'none') {
skill.style.display = 'grid'
} else {
skill.style.display = 'none'
};
};
skill1.onmousedown = showSkillInfo2(skill1Info);
谁能告诉我为什么第二个函数的工作方式与第一个函数不同?
此行:在定义
skill1.onmousedown = showSkillInfo2(skill1Info);
之前立即调用 skill
,因此它不起作用。
您需要做的就是将该行放入另一个函数中,并且该另一个函数将被分配为
mousedown
回调函数。
此外,你不需要在这里上两堂课。您可以只拥有一个始终有效的默认类,然后在
mousedown
时将其更改为新类。
最后,您不应该使用 HTML 事件属性来设置事件,因为这是一种在我们制定标准之前已有近 30 年历史的技术。相反,请将 HTML 和 JavaScript 分开。
请参阅下面的内嵌评论:
function showSkillInfo(event) {
// First, determine if the event occured on an element you care to handle
if(event.target.classList.contains("skill")){
// Just use the .toggle() method to toggle the use of a class.
// No if statement needed.
// event.target references the actual element that triggered the event
event.target.classList.toggle("grid");
}
};
// We'll just set up mousedown and mouseup events on a parent element
// of the possible elements that may need to be handled.
// by wrapping your callback inside of another function, you get the
// ability to set up the callback without invoking the "real" code
// that should wait for the event to happen. You can also pass the
// automatically provided reference to the event that triggered the
// callback to the function.
document.querySelector("div").addEventListener("mousedown", function(event) {
showSkillInfo(event);
});
document.querySelector("div").addEventListener("mouseup", function(event) {
showSkillInfo(event);
});
.skill {
color:aqua;
cursor:pointer;
}
.grid {
/* This is sample CSS. Replace with yours. */
color:red;
}
<div>
Lorem Ipsum is simply dummy text of the printing and typesetting industry.
Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,
when an unknown printer <span class="skill">took a galley</span> of type and
scrambled it to make a type specimen book. It has survived not only five
centuries, but also the leap into electronic typesetting, remaining essentially
unchanged. It was popularised <span class="skill">in the 1960s</span> with the
release of Letraset sheets containing Lorem Ipsum passages, and more recently
with desktop publishing software like Aldus PageMaker
<span class="skill">including versions</span> of Lorem Ipsum.
</div>
.onmousedown
属性是触发特定事件时调用的回调函数(在这种情况下鼠标按下,但所有其他事件的工作方式相同)。这意味着必须指定对函数或 lambda 函数的引用才能使其工作。第一个示例确实是对函数的引用并且按预期工作。另一方面,第二个是对函数的调用,它的返回值 (undefined
) 将受到 skill1.onmousedown
的影响。为了使其按预期工作,您需要指定一个将使用正确参数调用的新函数。最好的方法是使用 lambda 函数,如下所示:
skill1.onmousedown = () => showSkillInfo2(skill1Info);
这样,skill1.onmousedown
就具有无参数函数的值,并且可以在触发关联事件时调用它。