我正在尝试用其标签包装无线电输入,然后将一个元素插入新创建的包装器中,但是在输入和标签之间,我似乎无法找到一种简单的方法
我想转此
<fieldset data-radio-req>
<label>Choose Your Favorite</label>
<input type="radio" name="pokemon" value="Red">
<label>Red</label>
<input type="radio" name="pokemon" value="Blue">
<label>Blue</label>
<span class="form-error">This field is required.</span>
</fieldset>
进入这个
<fieldset data-radio-req>
<label>Choose Your Favorite</label>
<div class="toggle-box"> <!-- wrapper -->
<input type="radio" name="pokemon" value="Red">
<span><i></i></span> <!-- newly iserted -->
<label>Red</label>
</div>
<div class="toggle-box"> <!-- wrapper -->
<input type="radio" name="pokemon" value="Blue">
<span><i></i></span> <!-- newly iserted -->
<label>Blue</label>
</div>
<span class="form-error">This field is required.</span>
</fieldset>
目前我做
$('input[type="radio"]').each(function(index) {
$(this).next('label').andSelf().wrapAll("<div class='toggle-box'></div>");
});
但我不知道如何轻松地将'<span><i></i></span>'
插入到.toggle-box
和input
之间新创建的label
中,而无需另行.each()
答案 0 :(得分:1)
怎么样:
$('input[type="radio"]').each(function(index) {
$(this).next('label').andSelf().wrapAll("<div class='toggle-box'></div>").parent().append('<span><i></i></span>');
});
请查看下面的代码段。
$('input[type="radio"]').each(function(index) {
$(this).next('label').andSelf().wrapAll("<div class='toggle-box'></div>").parent().append('<span><i></i></span>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset data-radio-req>
<label>Choose Your Favorite</label>
<input type="radio" name="pokemon" value="Red">
<label>Red</label>
<input type="radio" name="pokemon" value="Blue">
<label>Blue</label>
<span class="form-error">This field is required.</span>
</fieldset>
或者如果您想要输入和标签之间的范围:
$('input[type="radio"]').each(function(index) {
$(this).next('label').andSelf().wrapAll("<div class='toggle-box'></div>").parent().find('label').before('<span><i></i></span>');
});
$('input[type="radio"]').each(function(index) {
$(this).next('label').andSelf().wrapAll("<div class='toggle-box'></div>").parent().find('label').before('<span><i></i></span>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset data-radio-req>
<label>Choose Your Favorite</label>
<input type="radio" name="pokemon" value="Red">
<label>Red</label>
<input type="radio" name="pokemon" value="Blue">
<label>Blue</label>
<span class="form-error">This field is required.</span>
</fieldset>