我正在尝试将参数传递给我创建的函数,但我想我错过了一些东西...... 这就是我想要做的:在事件鼠标悬停时,该单词及其翻译变为红色。当鼠标移出事件时,这两个词返回黑色。 我从这一点开始 - 纯 JavaScript(不涉及函数):
<span id ="e1" onmouseover="document.getElementById('c1').style.color='red'"
onmouseout = "document.getElementById('c1').style.color='black'"> House </span>
我知道我可以使用“this.style.color”,但对于我的最终目标来说它没有用...... 所以,我使用这种方法来创建一个函数。发生事件时,参数将传递给函数,并且它会为单词着色,并使用“getElementById”来标识它们。我认为这是一个好主意,而且它本来应该是:
<span id ="e1" onmouseover="color(e1,f1)" onmouseout="uncolor(e1,f1)"> House </span>
<span id ="f1" onmouseover="color(e1,f1)" onmouseout="uncolor(e1,f1)"> Maison </span>
<!-- The script in js would be: -->
<script>
function color(e, f) {
document.getElementById("e").style.color = "red";
document.getElementById("f").style.color = "red";
}
function uncolor(e, f) {
document.getElementById("e").style.color = "black";
document.getElementById("f").style.color = "black";
}
</script>
我知道这是传递参数的问题(我尝试将单个参数传递给包含“alert(arg)”的函数,但它不起作用)。我发现了一些事实,即该函数接收事件本身作为参数,但我真的不知道它是否是正确的方向或是什么......
任何提示将不胜感激,谢谢。
最佳答案
第一种方法
您需要进行 2 次更新。
更新 html(在参数周围添加引号)
<span id ="e1" onmouseover="color('e1','f1')" onmouseout="uncolor('e1','f1')"> House </span>
<span id ="f1" onmouseover="color('e1','f1')" onmouseout="uncolor('e1','f1')"> Maison </span>
更新您的脚本(在函数中使用时删除引号)
<script>
function color(e, f) {
document.getElementById(e).style.color = "red";
document.getElementById(f).style.color = "red";
}
function uncolor(e, f) {
document.getElementById(e).style.color = "black";
document.getElementById(f).style.color = "black";
}
</script>
第二种方法
没有 html 更新。将您的脚本更新为以下内容
<script>
function color(e, f) {
e.style.color = "red";
f.style.color = "red";
}
function uncolor(e, f) {
e.style.color = "black";
f.style.color = "black";
}
</script>
关于javascript - Js,将参数传递给事件函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32353159/