2012-03-06 66 views
1

我有這種格式我如何用一個div包裹投入使用jQuery

<td class="value"> 
<input type="text" size="30" name="application[name]" id="application_name" data-validate="true" class="name"> 
</td> 

,並與jQuery我需要最終的結果是這個

<td class="value"> 
<div class="field_with_errors"> 
    <input type="text" size="30" name="application[name]" id="application_name" data-validate="true" class="name"> 
    <label style="color: rgb(204, 0, 0);" class="message" for="application_name">Required</label> 
</div> 
</td> 

正如你可以看到我有一個包裝div ....我不認爲我可以實現這與prepend。這裏是我的jQuery,到目前爲止,正如你可以看到我有輸入

var form = $(".applications_form"); 
var company_name = form.find(".name"); 
+0

檢查http://api.jquery.com/wrap/ – 2012-03-06 16:09:35

回答

2

有一個wrap函數,該函數。

2

使用.wrapAll()功能,像這樣:

$('td.value').children().wrapAll('<div/>'); 

編輯:我的錯誤,我認爲<label>是在現有的HTML,當它似乎增加(雖然沒有那提!)。如果<input>確實是唯一存在的元素,那麼確實可以使用.wrap(),然後使用.append()在之後添加<label>元素。

可能是這樣的:

var company_name = $('#application_name'); // you have a unique ID, may as well make use of it! 
company_name.wrap('<div/>').parent().append('<label ...>'); 
2

看一看jQuery.wrap()

http://api.jquery.com/wrap/

$("#application_name").wrap("<div class=\"field_with_errors\"></div>"); 
$("#application_name .field_with_errors").append("<label style=\"color: rgb(204, 0, 0);\" class=\"message\" for=\"application_name\">Required</label>"); 

第一行包裝與div和2號線的輸入追加標籤。

0

試試這個

var $form = $(".applications_form"); 
var $company_name = $form.find(".name"); 
$company_name.wrap('<div class="field_with_errors" />');