使用jQuery为每个div添加一个标记

时间:2017-02-27 04:15:07

标签: javascript jquery html css

这是当前的代码:

  <div class="main-wrap">
    <div class="inner-wrap">
        some content here
        <span>
           <a href="1">test1</a>
        </span>
    </div>

    <div class="inner-wrap">
      some content here
      <span>
        <a href="2">test2</a>
      </span>
    </div>

    <div class="inner-wrap">
      some content here
      <span>
         <a href="3">test3</a>
     </span>
    </div>
 </div>

我需要在href attr中获取a tag span tag并将其插入整个inner-wrap元素。像这样:

  <div class="main-wrap">
    <div class="inner-wrap">
      <a href="1">
        some content here
        <span>
           <a href="1">test1</a>
        </span>
      </a>
    </div>

    <div class="inner-wrap">
     <a href="2">
      some content here
      <span>
        <a href="2">test2</a>
      </span>
     </a>
    </div>

    <div class="inner-wrap">
     <a href="3">
      some content here
      <span>
         <a href="3">test3</a>
     </span>
    </div>
   </a>
 </div>

我可以获取每个a tag的href标记,但我对如何将其附加到每个inner-wrap div感到困惑。这就是我到目前为止所做的:

$('.inner-wrap').each(function(){
    $this = $(this);
    $fetchLink = $this.children('span').find('a').attr('href');
    console.log($fetchLink);
});

我知道这真的很简单,但我无法解决这个问题。有人可以帮忙吗?

此处正在工作jsfiddle

2 个答案:

答案 0 :(得分:5)

您可以使用wrapInner(),但是,您应该将锚点嵌套在另一个锚元素中。

&#13;
&#13;
$('.inner-wrap').wrapInner(function(i) {
  var $this = $(this);
  var a = $this.children('span').find('a');
  var href = a.attr('href');

  //Remove inner anchor
  a.replaceWith(a.text());

  return "<a href='" + href + "'></a>";
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main-wrap">
  <div class="inner-wrap">
    some content here
    <span>
           <a href="1">test1</a>
        </span>
  </div>

  <div class="inner-wrap">
    some content here
    <span>
        <a href="2">test2</a>
      </span>
  </div>

  <div class="inner-wrap">
    some content here
    <span>
         <a href="3">test3</a>
     </span>
  </div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

由于您无法在链接中找到链接,因此效果不佳,但一般的想法是将$.html() .inner-wrap替换为$.html()包含在a标记中,$fetchLink作为href属性。

$('.inner-wrap').each(function() {
  $this = $(this);
  $fetchLink = $this.children('span').find('a').attr('href');
  $this.html('<a href="'+$fetchLink+'">'+$this.html()+'</a>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main-wrap">
  <div class="inner-wrap">
    some content here
    <span>
           <a href="1">test1</a>
        </span>
  </div>

  <div class="inner-wrap">
    some content here
    <span>
        <a href="2">test2</a>
      </span>
  </div>

  <div class="inner-wrap">
    some content here
    <span>
         <a href="3">test3</a>
     </span>
  </div>
</div>