【问题标题】:how to add Parent Element Name to Child Element如何将父元素名称添加到子元素
【发布时间】:2018-12-23 10:08:19
【问题描述】:

我有一个获取助手名称的输入元素,但两个元素具有相同的 id 编辑这个问题是不正确的, 我想将父 Div Id 添加到子 Input.how 我如何将 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

【问题讨论】:

  • 您可以使用其他属性,例如 ref,尽管 id 不会产生错误,您可以在子元素中给出 和子元素

标签: javascript jquery html model-view-controller


【解决方案1】:

下面的代码展示了如何使用.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>

【讨论】:

  • 非常感谢亲爱的@Oliver Trampleasure,它对我有一点帮助
  • 很高兴它有帮助!
猜你喜欢
  • 1970-01-01
  • 2013-03-19
  • 1970-01-01
  • 1970-01-01
  • 2019-10-16
  • 1970-01-01
  • 2019-02-12
  • 2022-01-12
  • 1970-01-01
相关资源
最近更新 更多