使用Jquery将选项组添加到选项列表中

3

我有以下HTML代码(请注意<\option>没有闭合标签),是由Lotus Domino生成的。

<select name="Fault" class="textbox">
<option>Single Light Out
<option>Light Dim
<option>Light On In Daytime
<option>Erratic Operating Times
<option>Flashing/Flickering
<option>Causing Tv/Radio Interference
<option>Obscured By Hedge/Tree Branches
<option>Bracket Arm Needs Realigning
<option>Shade/Cover Missing
<option>Column In Poor Condition
<option>Several Lights Out (please state how many)
<option>Column Leaning
<option>Door Missing/Wires Exposed
<option>Column Knocked Down/Traffic Accident
<option>Lantern Or Bracket Broken Off/Hanging On Wires
<option>Shade/Cover Hanging Open
<option>Other
</select>

使用 jQuery,我想在文档加载后将以下 HTML 转换为:

在第 11 个选项后添加一个 optgroup,并添加关闭的 </option> 标记。

<select name="Fault" class="textbox">
<option>Single Light Out</option>
<option>Light Dim</option>
<option>Light On In Daytime</option>
<option>Erratic Operating Times</option>
<option>Flashing/Flickering</option>
<option>Causing Tv/Radio Interference</option>
<option>Obscured By Hedge/Tree Branches</option>
<option>Bracket Arm Needs Realigning</option>
<option>Shade/Cover Missing</option>
<option>Column In Poor Condition</option>
<option>Several Lights Out (please state how many)</option>
    <optgroup label="Urgent Reasons">
<option>Column Leaning</option>
<option>Door Missing/Wires Exposed</option>
<option>Column Knocked Down/Traffic Accident</option>
<option>Lantern Or Bracket Broken Off/Hanging On Wires</option>
<option>Shade/Cover Hanging Open</option>
<option>Other</option>
    </optgroup>
</select>
2个回答

3

使用:nth-child(n+7)选择所有大于索引7的子元素。

$('option:nth-child(n+7)').wrapAll('<optgroup  label="Urgent Reasons">');

参见JsFiddle

非闭合的<option>是非法的HTML标记,我不确定jQuery如何处理它,因为它只进行有效的DOM操作。我建议您在解析HTML之前修复这些非闭合标记。


实际上,HTML 规范说明关闭 option 标签是可选的。 - Kerr

2

为了修复选项标签,如果您可以将HTML代码读入字符串中,则可以运行替换。类似于以下内容(由于我们正在谈论jQuery,因此这是一个JavaScript示例)

raw_code.replace(/(<option>.+)/g, "$1</option>\n");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接