[英]Js, passing arguments to a function on event
我正在嘗試將參數傳遞給我創建的函數,但是我想我缺少了一些東西……這就是我想要做的:在事件鼠標懸停時,單詞及其翻譯變紅。 在事件mouseout上,這兩個單詞將返回黑色。 我從這一點開始-純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>
通過使用(this)更簡單。
更新的代碼
<span id ="e1" onmouseover="color(this)" onmouseout="uncolor(this)"> House </span>
<span id ="f1" onmouseover="color(this)" onmouseout="uncolor(this)"> Maison </span>
通過使用“ this”,您可以將全部控件傳遞給功能。
function color(control) {
control.style.color = "red";
control.style.color = "red";
}
function uncolor(control) {
control.style.color = "black";
control.style.color = "black";
}
也許我沒有抓住重點,但是如果可能的話,所有這些都應該在CSS中完成。 您可以使用相鄰的同級選擇器+
或常規同級選擇器~
來獲取單詞后出現的翻譯。 但是,從翻譯到先前的兄弟姐妹沒有廣泛支持的方法。 解決該問題的最簡單方法是將兩個元素都放在另一個容器中。
簡化的HTML:
<div class="word-pair">
<span id ="e1" class="word"> House </span>
<span id ="f1" class="translation"> Maison </span>
</div>
CSS:
div.word-pair span{
color:#000;
transition:all .2s ease-in-out;
}
div.word-pair:hover span {
color:red;
}
小提琴示例: http : //jsfiddle.net/kw7wyux4/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.