我试图添加一个href标记并获取div的值,因为我需要使用jQuery在href标记上添加该值,我有这个代码
<div class="field-items">
<div class="field-item even">book
<div class="icon-more_link"></div>
</div>
<div class="field-item odd">pencil
<div class="icon-more_link"></div>
</div>
</div>
我想这样做:
<div class="field-items">
<div class="field-item even">
<a href="search/book">book</a>
<div class="icon-more_link"></div>
</div>
<div class="field-item odd">
<a href="search/pencil">pencil</a>
<div class="icon-more_link"></div>
</div>
</div>
你能帮我吗
答案 0 :(得分:4)
您需要使用.wrap功能。更多:http://api.jquery.com/wrap/
这里是代码:
$('.field-item').each(function(){
// to get text and remove any unwanted space
var link = $(this).text().trim();
$(this).wrap('<a href="search/'+ link +'"></a>');
});
JSfiddle:https://jsfiddle.net/Ljvjvbkq/23/
答案 1 :(得分:0)
这就是你需要的:
$(document).ready(function(){
$('.field-item').each(function(){
var search = $(this).text().trim();
$(this).wrap('<a href="search/' + search + '"></a>');
});
});
答案 2 :(得分:0)
您也可以尝试使用地图功能jquery map
var a = $("<a />");
$('.field-items > div.field-item').map(function(){
$(this)
.wrap($(a)
.attr('href','search/'+$(this).text().trim()));
return $(this);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="field-items">
<div class="field-item even">book
<div class="icon-more_link"></div>
</div>
<div class="field-item odd">pencil
<div class="icon-more_link"></div>
</div>
</div>
<div class="field-items">
<div class="field-item even">book-new
<div class="icon-more_link"></div>
</div>
<div class="field-item odd">pencil-new
<div class="icon-more_link"></div>
</div>
</div>