我需要帮助为我的项目制作脚本。
这就是代码的样子。
var thumbnails = document.getElementsByClassName("thumbnail");
var thumbnails_lenght = thumbnails.length;
for(var i=0; i<thumbnails_lenght; i++) {
thumbnails[i].onmouseover = function() {
//The problem part
};
thumbnails[i].onmouseout = function(){
};
}
*{
margin: 0 auto;
font-family: sans-serif;
}
.item{
width: 240px;
height: 240px;
margin: 5px;
background: #EEE;
}
.thumbnail{
width: 240px;
height: 200px;
background: #DDD;
}
.description{
width: 240px;
height: 40px;
line-height: 20px;
text-align: center;
font-size: 14px;
}
<div class="item">
<div class="thumbnail" id="1"></div>
<div class="description">test</div>
</div>
我需要这样做,当将鼠标悬停在具有特定类缩略图的div上以获取缩略图的ID时,每个缩略图div都会有它的ID,我需要获得该数字。
答案 0 :(得分:1)
var thumbnails = document.getElementsByClassName("thumbnail");
var thumbnails_lenght = thumbnails.length;
for(var i=0; i<thumbnails_lenght; i++) {
thumbnails[i].onmouseover = function(event) {
// You can get the id from the event passed to the handler:
alert('The id is: ' + event.target.id);
};
thumbnails[i].onmouseout = function(){
};
}
*{
margin: 0 auto;
font-family: sans-serif;
}
.item{
width: 240px;
height: 240px;
margin: 5px;
background: #EEE;
float: left;
}
.thumbnail{
width: 240px;
height: 200px;
background: #DDD;
}
.description{
width: 240px;
height: 40px;
line-height: 20px;
text-align: center;
font-size: 14px;
}
<div class="item">
<div class="thumbnail" id="1"></div>
<div class="description">test 1</div>
</div>
<div class="item">
<div class="thumbnail" id="2"></div>
<div class="description">test 2</div>
</div>
<div class="item">
<div class="thumbnail" id="3"></div>
<div class="description">test 3</div>
</div>
您的事件处理程序将收到一个事件对象。该对象将具有“target”属性,该属性是触发事件的元素。您可以从event.target获取ID。我已修改您的代码以提醒ID。