jQuery를 사용하여 가변 수의 어린이 요소를 감싸는 를 삽입하려면 어떻게합니까?
문제
다음과 비슷한 ASP.NET 코드가 있습니다 (이것은 필드 셋 안에 있습니다).
<ol>
<li>
<label>Some label</label>
<one or more form controls, ASP.Net controls, labels, etc.>
</li>
<li>
<label>Another label</label>
<... more of the same...>
</li>
...
</ol>
나는 마크 업을 가능한 한 깨끗하게 유지하려고 노력하고 있지만, 여러 가지 이유로 첫 번째 레이블 이후 목록 항목의 모든 주위에 div를 랩핑해야한다고 결정했습니다.
<ol>
<li>
<label>Some label</label>
<div class="GroupThese">
<one or more form controls, ASP.Net controls, labels, etc.>
</div>
</li>
<li>
<label>Another label</label>
<div class="GroupThese">
<... more of the same...>
</div>
</li>
...
</ol>
차라리 추가 마크 업으로 내 페이지를 쓰레기를 쓰지 않고 jQuery를 통해 "눈에 띄지 않는 JavaScript"로이 작업을 수행하여 의미 적으로 "깨끗하게"유지할 수 있습니다.
jQuery 선택기를 작성하여 각 목록 항목 $ ( "Li+Label")의 첫 번째 레이블에 도달하거나 사용 : First-Child를 사용하는 방법을 알고 있습니다. 또한 선택 후 물건을 삽입하는 방법도 알고 있습니다.
내가 알아낼 수없는 것은 (적어도 늦은 밤) 목록 항목의 첫 번째 레이블 이후에 모든 것을 찾는 방법입니다 (또는 기본적으로 첫 번째 레이블을 제외한 목록 항목의 모든 것이 다른 방법이 될 것입니다). 문서 준비 기능에서 그 주위에 div를 감싸십시오.
업데이트:
Owen의 코드는 주변에서 단일 따옴표를 제거한 후 작동했습니다.
$('this')적절한 치과 선택자를 설정하십시오.
$("li label:first-child")목록 항목 다음에 발생하는 첫 번째 레이블 만 선택하려면
여기에 내가 한 일은 다음과 같습니다.
$(document).ready(function() {
$('li label:first-child').each(function() {
$(this).siblings().wrapAll('<div class="GroupThese"></div>');
});
});
해결책
편집하다: 수정 된 코드 (개정 내역의 이전 코드 및 자세한 정보 참조)
Ok 이것은 작동해야합니다.
$('li label:first-child').each(function() {
$(this).siblings().wrapAll('<div class="li-non-label-child-wrapper">');
});
에서:
<li>
<label>Some label</label>
<div>stuff</div>
<div>other stuff</div>
</li>
<li>
<label>Another label</label>
<div>stuff3</div>
</li>
생산 :
<li>
<label>Some label</label>
<div class="li-non-label-child-wrapper">
<div>stuff</div>
<div>other stuff</div>
</div>
</li>
<li>
<label>Another label</label>
<div class="li-non-label-child-wrapper">
<div>stuff3</div>
</div>
</li>
다른 팁
한 가지 방법은u003Cli> 그런 다음 레이블을 꺼냅니다
var $div = $('li').wrapInner('<div></div>').children('div');
$div.children('label').prependTo($div.parent());
제휴하지 않습니다 StackOverflow