2012-01-23 29 views
2

我有多個div,我試圖做一個功能,當用戶鼠標在div上。在div的內部可以有任意數量的「子」div,我需要在函數內訪問它們。我似乎無法做到這一點。這裏是什麼,我試圖做一個例子:無法訪問jquery中的子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> 

的腳本:

function modelMouseOver2() { 
// I'm not sure what to do here to access the child divs. 
$(this).children("div").each(function (i) { 
    $(this).hide(); 
}); 
} 
+0

可以在jsfiddle中添加 – Ghostman

回答

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(); 
}); 
} 

第一 「這」 指的是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; 
3

嘗試使用find()

$(this).find("div").hide(); 

但是,如果你開始使用jQuery你可能使用jQuery本身訂閱文檔加載事件:

$(function() { 
    $('div#div_test').hover(function() { 
     $(this).find('div').hide(); 
    }, function() { 
     $(this).find('div').show(); 
    }); 
}); 
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

你可以做一些這樣的事

$(this).find("div").each(function() { 
      $(this).hide(); 
     });