这是当前的代码:
<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
答案 0 :(得分:5)
您可以使用wrapInner()
,但是,您应该不将锚点嵌套在另一个锚元素中。
$('.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;
答案 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>