【问题标题】:jQuery transfer the ID to another element of the same parentjQuery 将 ID 传递给同一个父元素的另一个元素
【发布时间】:2019-01-16 07:50:16
【问题描述】:

使用此代码,每个<ul>class="myDropDown" 都有相同的结果。我的问题是var getID。我希望每个<div class="dropDownInner"> 都能获得创建它的<ul> 的ID。我该如何解决这个问题?

$(document).ready(function() {
  var getID = $(".myDropDown").attr('id');
  $(".myDropDown").wrap('<div class="customDropDown"></div>');
  $(".customDropDown").prepend('<div class="dropDownHeader">');
  $(".dropDownHeader").append('<div class="dropDownInner" id="' + getID + '">Select One</div>');
  $(".dropDownHeader").append('</div>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ul class="myDropDown" id='testSelect'>
  <li>Item 1</li>
  <li>Item 2</li>
</ul>

<ul class="myDropDown" id='testList'>
  <li>Item 1</li>
  <li>Item 2</li>
</ul>

【问题讨论】:

  • ID 应该是唯一的。您尝试做的事情毫无意义。
  • 无论如何,要做你想做的事,你必须遍历每个.myDropDown。使用this.id获取其ID,添加包装器时使用$(this)

标签: javascript html jquery html-lists


【解决方案1】:

这样您可以获取与每个 ul 元素关联的 ID。

$('.myDropDown').each(function(index) {
    // Execute the below code for each element with class .myDropdown
    var id = $(this).closest('ul.myDropDown').attr('id');  
    $(this).wrap('<div class="customDropDown"></div>');
    $(this).prepend('<div class="dropDownHeader">');
    $(this).closest('div').prepend('<div class="dropDownInner" id="' + id + '">Select One</div>');
    $(this).append('</div>');
});

这与您的代码具有相同的 DOM 结构,具有您正在寻找的不同 ID

编辑:Barmar 提出了一个公平的观点。 ID 应该在每个页面上只使用一次。我建议将 ID 更改为类。但是,这将涉及更多代码。

【讨论】:

  • 就是这个!!我稍微更改了代码,但解决方案的根源就是这个。谢谢你。我也需要 id 所以我用了这个$(this).removeAttr("ID");
猜你喜欢
  • 2012-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多