javascript - 如何找到 DIVS 的 ID,并将这些名称作为类分配给其他 DIVS?

标签 javascript jquery addclass

我是 jquery 的新手,无法理解这一点。我有 3 个具有不同 ID 的 div,但都以“sharedform”开头。我想遍历这些 div,获取每个 id 并将其作为标识类分配给每个之前的“slideHead”div。任何帮助将不胜感激!

HTML:

<div class="slideHead">
</div>
<div class="drawer">
  <div id="sharedform.upload_image">
          <p></p>
  </div>
</div>
<div class="slideHead">
</div>
<div class="drawer">
   <div id="sharedform.Event">
       <p></p>
   </div>
</div>
<div class="slideHead">
</div>
<div class="drawer">
    <div id="sharedform.BackGround_All">
        <p></p>
    </div>
 </div>

j查询:

var $getclass = $(".drawer");
    addclass = $getclass.find('[id^="sharedform"]').attr('id');
$(".slideHead").addClass(addclass);

最佳答案

我建议:

// get all elements whose id starts with 'sharedform', iterate over that collection:
$('div[id^=sharedform]').each(function (){
    // find the parent of the 'this' element:
    $(this).parent()
    // find the previous element, if it matches the passed-in selector:
    .prev('.slideHead')
    // add the id of the element we initially selected as a class:
    .addClass(this.id);
});

$('div[id^=sharedform]').each(function() {
  $(this).parent().prev('.slideHead').addClass(this.id);
});
div {
  width: 80%;
  margin: 0 auto;
  min-height: 2em;
  padding: 0.5em;
  border: 1px solid #000;
}
.slideHead {
  background-color: #f00;
}
.slideHead.sharedform\.something {
  background-color: #0f0;
}
<div class="slideHead"></div>
<div>
  <div id="sharedform.something">some text in the div</div>
</div>

但请注意,考虑到在 id 中包含句点 (.),这些类名是有问题的。

关于javascript - 如何找到 DIVS 的 ID,并将这些名称作为类分配给其他 DIVS?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26660765/

相关文章:

javascript - 重新加载 div 后,jQuery 悬停功能不起作用

jquery - foreach 输入多维数组

jquery - addClass removeClass 在 IE 中不工作..!

javascript - 如何使用多个变量来创建多个jquery选择器?

javascript - JS onkeydown/onkeyup - 转换为 jQuery keydown/keyup

javascript - 在 HTML5 视频元素中播放电影时如何在 IOS 上显示非全尺寸视频?

javascript - Promise.all() 未按预期顺序解决 promise

jquery lightGallery 插件在侧面/边缘显示图像

javascript - HTML jQuery 选择选项值

Jquery 删除类多个元素