1

我有一组像

<a class="lb" href="#">text</a>
<a class="lb" href="#" style="width:200px">text</a>
<a class="lb" href="#" style="color: reen; width:200px">text</a>

这需要转换为以下内容:

<a class="lb" href="#"><span>text</span></a>
<a class="lb" href="#"><span style="width:200px">text</span></a>
<a class="lb" href="#" style="color:green"><span style="width:200px">text</span></a>

我创建孩子没有问题span,但不知道如何移动父母的width样式。

4

2 回答 2

4

对于您的示例,.wrapInner().css()函数应该这样做。例子:

$(document).ready(function(){
   var $anchors = $('a');
   $anchors.wrapInner('<span></span>');

   $anchors.children('span').each(function(i,v){
      $(this).css('width', $(this).parent().css('width'));
   });
});

描述:围​​绕匹配元素集中每个元素的内容包装一个 HTML 结构。

请注意,在此示例代码中,您的标记中的所有锚点都将被匹配。您可能希望更具体地使用classesids

于 2010-06-14T07:08:42.327 回答
0

应该这样做 - 设置一个内部<span>,并复制在中指定的任何 css 属性to_be_moved

$('.lb').each(function(){
    $(this).wrapInner('<span/>');
    var to_be_moved = ['width']; // array of css attributes to move
    for (var i=0;i<to_be_moved.length;i++){
        // get current value
        var currentValue = $(this).css(to_be_moved[i]);
        // set current value to nothing
        $(this).css(to_be_moved[i], '');
        // place the value into the child span
        $(this).children('span').css(to_be_moved[i], currentValue);
    }
});
于 2010-06-14T07:31:46.700 回答