我有多个div,当用户将鼠标悬停在div上时,我正在尝试执行某个功能。在div内部可以有任意数量的“子”div,我需要在函数内访问它们。我似乎无法做到这一点。这是我正在尝试做的一个例子:
<div id='div_test' onmouseover='modelMouseOver2()' onmouseout='modelMouseOut()'>
<div id = "model1"><img src="img/circle.png" alt="" /></div>
<div id = "model2" class='models' onmouseover="modelMouseOver2()" onmouseout="model2MouseOut()" style=" width: 40px; height: 40px;"><img src="img/circle2.png" alt="" />
<div><img src="img/circle3.png" alt="" /></div>
<div><img src="img/circle4.png" alt="" /></div>
<div><img src="img/circle2.png" alt="" /></div>
</div>
<div id = "model3" class='models' onmouseover="modelMouseOver2()"><img src="img/circle3.png" alt="" /></div>
<div id = "model4" class='models' onmouseover="modelMouseOver2()"><img src="img/circle4.png" alt="" /></div>
<div id = "model5" class='models' onmouseover="modelMouseOver2()"><img src="img/circle5.png" alt="" /></div>
</div>
for the script:
function modelMouseOver2() {
// I'm not sure what to do here to access the child divs.
$(this).children("div").each(function (i) {
$(this).hide();
});
}
答案 0 :(得分:3)
尝试使用find()
$(this).find("div").hide();
但是如果你开始使用jQuery,你可以使用jQuery本身订阅你的文档加载事件:
$(function() {
$('div#div_test').hover(function() {
$(this).find('div').hide();
}, function() {
$(this).find('div').show();
});
});
答案 1 :(得分:2)
尝试像这样的js
(function($){
$('#div_test').hover(
function(){
// this is the mouse over
// this selects all the div inside
$(this).find('div');
},
function(){
// this is the mouse out
// this selects all the div inside
$(this).find('div');
}
);
})(jQuery);
答案 2 :(得分:2)
你可以做这样的事情
$(this).find("div").each(function () {
$(this).hide();
});
答案 3 :(得分:1)
问题在于:
function modelMouseOver2() {
// I'm not sure what to do here to access the child divs.
$(this).children("div").each(function (i) { // here
$(this).hide();
});
}
第一个“this”指的是DOM窗口。
这里有两种选择。第一个是在内联事件中传递this
,第二个是在javascript中设置事件:
<强>内联强>
<div id='div_test' onmouseover='modelMouseOver2(this)' onmouseout='modelMouseOut()'>
和内联的javascript:
function modelMouseOver2(xthis) {
// I'm not sure what to do here to access the child divs.
$(xthis).children("div").each(function (i) {
$(this).hide();
});
}
或者,通过javascript设置onmouseover:
document.getElementById('div_test').onmouseover=modelMouseOver2;