![](/img/trans.png)
[英]javascript: how to add an attribute to a child element ONLY if a parent element is active AND child element has a certain class?
[英]how to add Parent Element Name to Child Element
我有一個獲取 Helper 名稱的輸入元素,但兩個元素具有相同的 id 編輯此問題不正確,我想將父 Div Id 添加到子輸入。如何將 ParentId 附加到 ChildId
<div class="wrapper-merge-input">
<div id="Stb" class="col-md-6 ">
<label class="control-label">StartDate</label>
@page.Html.Raw(fromHtml)
</div>
<div id="Edb" class="col-md-6 ">
<label class="control-label">EndDate</label>
@page.Html.Raw(toHtml)
</div>
</div>
</div>
*和 *
<input type="text" dir="ltr" class="form-control"
name="@name" id="@name"
value="@value"
onclick="DatePicker.Show(this,'@today');" />
例如@name+Edb
下面的代碼顯示了如何使用.attr("id")
來獲取元素的id
。 為了向上移動一級到父 DOM 元素,您應該使用.parent()
。
您還可以使用.attr("id", "new-id")
來設置屬性值。 這可以采用字符串或變量(如下面的代碼所示)。
通過將更新代碼放入函數中,您可以在頁面加載、單擊或任何其他事件后調用它。 我已經讓它在點擊按鈕后運行,所以你可以看到id
變化。
我添加了一些基本樣式以使演示更好用。
如果你想要別的東西,請告訴我。
警告您可能希望使
updateID()
函數更具體,因此它不會對頁面上的每個輸入起作用。
// Click event for button to demonstrate change $("#startUpdate").click(function() { updateID(); }); function updateID() { // Cycle through each input - WARNING - you will want to make this more selective $("input").each(function() { // Update id of input from it's own name and it's immediate parent's id $(this).attr("id", $(this).attr("name") + "-" + $(this).parent().attr("id")); // Print message to console to demonstrate id console.log("new id = " + $(this).attr("id")); }); }
.wrapper-merge-input { border: 1px solid black; border-radius: 5px; padding: 8px; margin: 20px; } #Edb { padding-top: 10px; } #startUpdate { margin-left: 20px; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="wrapper-merge-input"> <div id="Stb" class="col-md-6 "> <label class="control-label">StartDate</label> <input name="example1" id="example1" value="example1" onclick="DatePicker.Show(this,'@today');"> </div> <div id="Edb" class="col-md-6 "> <label class="control-label">EndDate</label> <input name="example2" id="example2" value="example1" onclick="DatePicker.Show(this,'@today');"> </div> </div> <button id="startUpdate">Update IDs</button>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.