2010-06-14 34 views
1

我有一組錨狀jQuery的腳本來匹配元素的屬性轉移到自己的孩子

<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

對於你的例子,.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結構。

注意,在這個示例代碼,您的標記中的所有anchros將被匹配。你可能想通過使用classesids

+0

這是沒有問題的我。真正的問題是將錨的寬度移動到兒童跨度:( – UserControl 2010-06-14 07:14:57

0

這應該這樣做更具體的 - 集內<span>,並複製無論是在to_be_moved指定的CSS屬性了:

$('.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); 
    } 
});