我正在尝试格式化和更改标准HTML表单的结构。目前输出看起来像这样
<form accept-charset="UTF-8" autocomplete="off" method="POST">
<ol class="questions">
<div>
<label>First Name *</label>
<input type="text" />
</div>
<div>
<label>Email *</label>
<input type="text" />
</div>
<div class="submit">
<input type="submit" value="Submit" />
</div>
</ol>
</div>
</form>
我需要将div更改为列出项目,然后在可能的情况下在标签周围添加范围。
到目前为止我已经得到了这个但不幸的是它并没有改变。
window.onload = function() {
var widgetHTML = $('ol.questions').html();
widgetHTML = widgetHTML
.replace(/<div>/g, '<li>')
.replace(/<\/div>/g, '</li>');
$('ol.questions').html(widgetHTML);
};
添加跨度并将DIV替换为LI的任何想法都很棒
答案 0 :(得分:1)
使用.replaceWith()
和.wrap()
:
$("form div").replaceWith(function(){
$(this).find('label').wrap('<span/>');
return $('<li>' + this.innerHTML + '</li>')
});
<强> jsFiddle example 强>
这会给你:
<form accept-charset="UTF-8" autocomplete="off" method="POST">
<ol class="questions">
<li>
<span><label>First Name *</label></span>
<input type="text">
</li>
<li>
<span><label>Email *</label></span>
<input type="text">
</li>
<li>
<input type="submit" value="Submit">
</li>
</ol>
</form>
答案 1 :(得分:1)
这应该这样做。
$('ol.questions div').each(function(){
$('label',this).wrap('<span/>');
var children = $(this).children();
$(this).replaceWith($('<li/>').append(children));
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form accept-charset="UTF-8" autocomplete="off" method="POST">
<ol class="questions">
<div>
<label>First Name *</label>
<input type="text" />
</div>
<div>
<label>Email *</label>
<input type="text" />
</div>
<div class="submit">
<input type="submit" value="Submit" />
</div>
</ol>
</form>
&#13;
答案 2 :(得分:0)
使用以下jQuery函数更改类型:
(function($) {
$.fn.changeElementType = function(newType) {
var attrs = {};
$.each(this[0].attributes, function(idx, attr) {
attrs[attr.nodeName] = attr.nodeValue;
});
this.replaceWith(function() {
return $("<" + newType + "/>", attrs).append($(this).contents());
});
}
})(jQuery);
// USAGE
$("div").changeElementType("li");
(https://stackoverflow.com/a/8584217/1017882)
使用以下代码用span填充标签:
$("label").wrap("<span></span>");
注意:您需要根据需要优化选择器。上面的选择器将根据您发布的标记生效,但我假设您的页面上还有其他div和标签。