这是一个小小的故事......我想制作一个for循环,让make成为addenventlisteners所以当我移动时:hover / onmouseover它应该移动2种颜色。但是我无法弄清楚如何将关键字转换为函数redB ...
但是我不知道我是否在严格的方式......
$(document).ready(function() {
var i;
for (i = 0; i < 10; i++) {
document.getElementById("sek2" + i + ).addEventListener("mouseover", Over(this));
document.getElementById("sek2" + i + ).addEventListener("mouseout", Out(this));
}
});
function greyB(x) {
x.style.backgroundColor = "grey";
}
function redB(x) {
x.style.backgroundColor = "red";
}
答案 0 :(得分:0)
你正在调用错误的function
名称,如果你使用$(document).ready()
,你需要啊jquery库
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Js代码
$(document).ready(function() {
var i;
for (i = 0; i < 10; i++) {
document.getElementById("sek2" + i + ).addEventListener("mouseover", greyB);
document.getElementById("sek2" + i + ).addEventListener("mouseout", redB);
}
});
function greyB() {
this.style.backgroundColor = "grey";
}
function redB() {
this.style.backgroundColor = "red";
}
答案 1 :(得分:0)
使用vanilla javascript,接近当前代码,这很简单:
var i;
for (i = 0; i < 1; i++) {
document.getElementById("sek2" + i).addEventListener("mouseover", function(){ greyB(this); });
document.getElementById("sek2" + i).addEventListener("mouseout", function(){ redB(this); });
}
function greyB(x) {
x.style.backgroundColor = "grey";
}
function redB(x) {
x.style.backgroundColor = "red";
}
&#13;
<div id="sek20">Mouse over me</div>
&#13;
如果使用jQuery,这更容易:
$("[id^='sek2']").on('mouseover', function(){
$(this).css('background-color','grey');
}).on('mouseout',function(){
$(this).css('background-color','red');
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="sek20">Mouse over me</div>
&#13;
答案 2 :(得分:0)
这就是你想要的东西吗?
$(document).ready(function() {
var i;
for (i = 0; i < 10; i++) {
let newDiv = document.createElement('div');
newDiv.classList.add('square');
newDiv.addEventListener("mouseover", greyB);
newDiv.addEventListener("mouseout", redB);
document.querySelector('body').appendChild(newDiv);
}
});
function greyB() {
this.style.backgroundColor = "grey";
}
function redB() {
this.style.backgroundColor = "red";
}
.square {
background-color: red;
width: 100px;
height: 100px;
margin: 10px;
display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
答案 3 :(得分:0)
我结束了这个解决方案,但任何人都可以告诉那里获取有关此代码的更多信息。什么样的语言可能是某个地方的链接。所以我没有得到不同的代码来进一步发挥。
谢谢...
var i;
for (i = 0; i < 1; i++) {
document.getElementById("sek2" + i).addEventListener("mouseover", function(){ greyB(this); });
document.getElementById("sek2" + i).addEventListener("mouseout", function(){ redB(this); });
}
function greyB(x) {
x.style.backgroundColor = "grey";
}
function redB(x) {
x.style.backgroundColor = "red";
}
&#13;
<div id="sek20">Mouse over me</div>
&#13;