[英]get id from a nested div using jquery
我不知道怎么寫這個。 這已經有點亂了。 我不能用正確的詞來問這個問題。 這是我的代碼:
<div id="addfieldcontainerdropdown"> <div id="addDropdownfield"> <div id="div0"> <select name="0" style="margin: 20px" id="0"> <option value="1">1</option> <option value="2">2</option> </select> <input style="margin: 7px" id="1" placeholder="Value" onkeyup="check_if_value_set(this); return false;" type="text"> <span style="margin: 7px;cursor: pointer;" onclick="remove_fields(this);return false;"><iclass="fa fa-times"></i></span> </div> <div id="div2"> <select name="2" style="margin: 20px" id="2"> <option value="1">1</option> <option value="2">2</option> </select> <input style="margin: 7px" id="3" placeholder="Value" onkeyup="check_if_value_set(this); return false;" type="text"> <span style="margin: 7px;cursor: pointer;" onclick="remove_fields(this);return false;"><i class="fa fa-times"></i></span> </div> <div id="div4"> <select name="4" style="margin: 20px" id="4"> <option value="1">1</option> <option value="2">2</option> </select> <input style="margin: 7px" id="5" placeholder="Value" onkeyup="check_if_value_set(this); return false;" type="text"> <span style="margin: 7px;cursor: pointer;" onclick="remove_fields(this);return false;"><i class="fa fa-times"></i></span> </div> </div> <a href="javascript:void(0)" onclick="show_new_text_field(this);event.preventDefault();return false;" style="cursor:pointer"> <span id="add_new_span" class="addnew" style="float: none;margin-left: 1%;"><i class="fa fa-plus fa-fw"></i>Add New Field</span> </a> </div>
您可以看到代碼底部有一個名為“show_new_text_field(this)”的函數。 使用此功能,我需要獲取 div4 的 id 或 id 4 的選擇框。如何做到這一點? 我嘗試使用 prent() 和最接近的()。 沒有任何效果。 任何類型的建議將不勝感激。 提前致謝!!
像這樣的東西?
var lastDiv = $("[id^=div]").last(); //Get Last div whose ID begins with "div"
var lastDivId = lastDiv.attr('id'); //Get ID of that div
var firstSelect = lastDiv.find('select').first(); //Get the first 'select' of that div
var firstSelectId = firstSelect.attr('id'); //Get that select's ID
console.log("Last Div: " + lastDivId); // "Last Div: div4"
console.log("First Select in " + lastDivId + ": " + firstSelectId); //"First Select in div4: 4"
如果您的 div 並不總是以“div”開頭,您可以通過執行以下操作來選擇父級的最后一個子div
( addDropdownfield
):
var lastDiv = $("#addDropdownfield div").last(); //Get all children divs of addDropdownfield - from that list, just the last one
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.