0

我有以下代码:

<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>")了,但这会在输入元素周围创建一个包装器,但不包括“复选框 field_1 ....”

4

5 回答 5

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/>')
于 2011-07-27T21:12:35.823 回答
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 />");
于 2011-07-27T20:52:47.440 回答
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"]'));
于 2011-07-27T20:48:26.790 回答
0

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

IE

<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" />');

然后用不同的班级做第二部分

于 2011-07-27T20:58:19.610 回答
-1

它应该工作:

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

点击这里

于 2011-07-27T20:52:44.047 回答