[英]jQuery to select div inside div inside form
我有這個代碼:
$(document).ready(function() { $form.find() });
#second { font-size: 20px; color: green; background: white; text-align: center; }
<form> <div class="first" style="width: 301px; margin:5px 0 0 10px;"> <div id="second" style="font-size:18px; position: absolute; top: 8px; left: 5px; width: 300px; height: 42px;">Hello</div> </div> </form>
我想選擇id="second"
的div
,以便將background
更改為red
。 有沒有使用find()
做到這一點的解決方案。
對我來說最重要的是使用它的id
選擇div
。 的jsfiddle
為什么不這樣做呢?
$(document).ready(function() { $("#second").css("background-color", "red") });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form> <div class="first" style="width: 301px; margin:5px 0 0 10px;"> <div id="second" style="font-size:18px; position: absolute; top: 8px; left: 5px; width: 300px; height: 42px;">Hello</div> </div> </form>
您可以使用#second
找到該元素,然后使用此更改顏色。 如果您願意,可以將其綁定到click
事件,或者您想要更改background-color
任何方式。
如果你打算使用find()
你可以做到這一點,並且你想要找到多個元素,你可以這樣做
$(document).ready(function() { $("form").find("#second, #fourth").css( "background-color", "red" ); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form> <div class="first"> <div id="second">Hello</div> <div id="third">World</div> <div id="fourth">World</div> </div> </form>
您可以使用逗號分隔它們,從而根據需要定位任意數量的元素。
或者作為形式的下降:
$(document).ready(function() {
$("form").find( "div#second" ).css( 'background-color', 'red');
});
$(document).ready(function() {
$("form").find( "div#second" ).addClass('red');
});
CSS
.red{
background-color: red;
}
如果你事先確定div id,那么使用.find()可能會有點多余,因為你可以簡單地使用jquery selector $("#second")
。
如果您想使用.find(),只需要指定搜索開始的位置(在您的情況下為表單)以及您希望如何過濾搜索
所以會:
$("form").find("#second")
然后你可以將它鏈接到.css()
或將其添加到變量或其他:)
$(document).ready(function() {
$("form div").find( "div" ).css( 'background-color', 'black');
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.