使用jQuery包装输入元素组

时间:2011-07-27 20:42:16

标签: javascript jquery wrapall

我有以下代码:

<input type="checkbox" name="field_1" value="on" /> Checkbox field_1
<input type="checkbox" name="field_1" value="off" /> Checkbox field_1


<input type="checkbox" name="field_2" value="on" /> Checkbox field_2
<input type="checkbox" name="field_2" value="off" /> Checkbox field_2

我需要用jQuery包装这些元素。看起来应该是这样的:

<div>
<input type="checkbox" name="field_1" value="on" /> Checkbox field_1
<input type="checkbox" name="field_1" value="off" /> Checkbox field_1
</div>
<div>
<input type="checkbox" name="field_2" value="on" /> Checkbox field_2
<input type="checkbox" name="field_2" value="off" /> Checkbox field_2
</div>

我尝试了$("input[name=field_1]".wrappAll("<div></div>")但这会在输入元素周围创建一个包装器,但不会包含“Checkbox field_1 ....”

5 个答案:

答案 0 :(得分:2)

我建议您修改现有代码,使其成为:

<label><input type="checkbox" name="field_1" value="on" /> Checkbox field_1</label>
<label><input type="checkbox" name="field_1" value="off" /> Checkbox field_1</label>

<label><input type="checkbox" name="field_2" value="on" /> Checkbox field_2</label>
<label><input type="checkbox" name="field_2" value="off" /> Checkbox field_2</label>

这不仅可以简化您的jQuery代码(因为jQuery非常适合使用标记节点而不是很好地处理文本节点),而且还可以提高可访问性,因为复选框后的标签将变得可点击。

然后在jQuery中:

$('input[name="field_1"]').parent().wrapAll('<div/>')

答案 1 :(得分:0)

试试这个:

function wrapFieldSet(fields) {
    var wrapper = $('<div class="wrapper"></div>');
    fields.first().before(wrapper);
    fields.each(function() {
        var text = $(this.nextSibling);
        wrapper.append($(this)).append(text);
    });
}

wrapFieldSet($('input[name="field_1"]'));

答案 2 :(得分:0)

试试这个

var $div = $("<div />"), next, $this;

$("input[name=field_1]:first").before($div);
$("input[name=field_1]").each(function(){
  $this = $(this);
  next = $this.next();
  $div.append($this);
  $div.append(next)
});

$div = $("<div />");

答案 3 :(得分:0)

我打算建议在标签中包装Checkbox field_1等,为每个标签添加类并使用此包装示例jQuery API来实现您的目标

<input id="foo1" class="bar" type="checkbox" name="field_1" value="on" /> 
<label class="bar" for="foo1">Checkbox field_1</label>
<input id="foo2" class="bar" type="checkbox" name="field_1" value="off" />
<label class="bar" for="foo2">Checkbox field_1</label>

然后使用

$('.bar').wrap('<div class="something" />');

然后使用不同的类

执行第二部分

答案 4 :(得分:-1)

应该有效:

$('input[name=field_1]').wrapAll('<div />');

Click Here

相关问题