我不知道怎么说这个。这有点乱。我不能用写字来提问。这是我的代码:
<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)”的函数。使用这个函数,我需要获取说id,div4的id或选择id的框4.如何做到这一点?我尝试使用prent()和nearest()。没有任何效果。任何类型的建议将不胜感激。 在此先感谢!!
答案 0 :(得分:5)
这样的东西?
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不会总是以&#34; div&#34;开头,你可以通过这样做选择你父母的最后一个孩子div
(addDropdownfield
) :
var lastDiv = $("#addDropdownfield div").last(); //Get all children divs of addDropdownfield - from that list, just the last one