用jQuery添加标签

时间:2014-08-07 03:59:19

标签: jquery html tags

我的标记看起来像这样:

<ul>
    <li><span class="mystyle">List Item 1</span></li>
    <li><span class="mystyle">List Item 2</span></li>
    <li><span class="mystyle">List Item 3</span></li>
</ul>

我希望它看起来像这样:

<ul>
    <li><span class="mystyle"><a href="#">List Item 1</a></span></li>
    <li><span class="mystyle"><a href="#">List Item 2</a></span></li>
    <li><span class="mystyle"><a href="#">List Item 3</a></span></li>
</ul>

使用jQuery,如何使用“mystyle”类为所有元素添加HTML标记?

5 个答案:

答案 0 :(得分:4)

使用.wrapInner()。试试这个:

$('.mystyle').each(function(){
    $(this).wrapInner('<a href="#"></a>');
});

<强> DEMO

答案 1 :(得分:2)

首先,您的标记不正确,需要关闭使用的span标记。然后你可以使用JS:

$('.mystyle').each(function(){
  $(this).html('<a href="#">List Item '+$(this).html()+'</a>');
});

答案 2 :(得分:2)

使用jQuery.wrap() --- DEMO

$('.mystyle').contents().wrap( $('<a/>',{href:'#'}) );

jQuery.wrapInner() --- DEMO

$('.mystyle').wrapInner( $('<a/>',{href:'#'}) );

.wrap() - 在匹配元素集合中围绕每个元素包装HTML结构

.wrapInner() - 围绕匹配元素集中的每个元素的内容包装。

答案 3 :(得分:2)

 $(".mystyle").each(function () {

    $(this).html('<a href="#">' + $(this).text() + '</a>');
});

答案 4 :(得分:2)

使用此

$('.mystyle').each(function(){
    $(this).html('<a href="#">'+$(this).text()+'</a>');
});

.html使用新内容覆盖元素的旧html,作为参数给出。