我有Lotus Domino生成的以下HTML代码(请注意<\option>
上没有结束标记)。
<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>
答案 0 :(得分:3)
使用:nth-child(n+7)
,您可以选择大于索引7的所有子项。
$('option:nth-child(n+7)').wrapAll('<optgroup label="Urgent Reasons">');
请参阅JsFiddle
非关闭<option>
是无效的HTML,因此我不确定jQuery如何处理这个问题,因为它只是执行有效的DOM操作。我建议您在解析HTML之前修复此非结束标记。
答案 1 :(得分:2)
要修复选项标记,如果您可以将HTML代码读取为允许您运行替换的字符串。类似的东西(这是一个javascript示例,因为我们讨论的是jQuery)
raw_code.replace(/(<option>.+)/g, "$1</option>\n");