2013-06-23 35 views
1

我可以在jquery $(this+"#id").html(...);或其他任何方法中使用。
我有這樣的情況下使用這樣的。下面

HTML代碼

<div id="box1"> 
<div ></div> 
</div>  

CSS代碼我的代碼被賦予是

#box1 { 
width:300px; 
height:200px; 
border:1px solid #333; 
} 
#box1 div 
{ 
width:200px; 
height:150px; 
border:1px solid #999; 
margin:auto; 
margin-top:10px; 

} 

jQuery代碼是

$(document).ready(function() 
       { 
        $("#box1").mouseenter(function() 
     { 

     $(this+"div").html("<p>Mouse entered</p>"); 

     }); }); 

jsfiddle

+3

使用合理的,一致的代碼縮進將幫助您防止錯誤,並且在有問題時幫助人們幫助您。所有應有的尊重,但問題結尾處的代碼塊只是一個完整的災難。 –

回答

1

嘗試牛逼我的代碼他的一個:

$(document).ready(function() 
{ 
    $("#box1").mouseenter(function() 
    { 
     $("div", this).html("<p>Mouse entered</p>"); 
    });  
}); 

這裏是jsFiddle

+0

你可以在你的評論中添加一些解釋給你的代碼 – rlemon

+1

@ VladIoffe你的報價是錯位的。 – Brombomb

+0

謝謝@ Brombomb。當你試圖選擇某個元素內部的某些元素時,這是它的一個方法$(「this_child_selector」,this)。還有很多,但對我來說它乾淨而快速 – vlio20

4
$(document).ready(function() { 
    $("#box1").mouseenter(function() { 
     // $(this) references the #box1 element, and turns it into a jquery object 
     // .find searches inside this DOM node for the new selector 
     $(this).find("div").html("<p>Mouse entered</p>"); 
    });  
}); 

.find method - 一個新的選擇的DOM元素內搜索。將匹配返回爲jQuery對象。

我重新格式化了您的代碼,以使用我們在工作中使用的約定。請注意,開放曲線位於同一行,然後匹配關閉縮進到其開放級別。有很多「最佳實踐」,所以試着找到一個並堅持下去。這將使閱讀,理解和調試代碼變得更加容易。

+1

你能否給你的代碼添加一些解釋? – rlemon

1

嘗試使用

$(this).find("div").html("<p>Mouse entered</p>");