我试图让jQuery在文本输入之前在"untagged“元素上设置一个标签。但是,它似乎是在设置前一个标记上的标签。我无法在代码中手动设置标签,因为它是自动生成的,插件开发人员已经删除了表单字段上的标签。下面是我目前拥有的一个字段的代码:
<div id="_dgx_donate_donor_first_name" class="text-input-section">
<div id="_dgx_donate_donor_first_name-error-message" style="display:none" class="seamless-donations-error-message-field"></div>
First Name:
<input type="text" name="_dgx_donate_donor_first_name" value="" size="20" data-validate="required" id="text_dgx_donate_donor_first_name" class="text-box">
</div>当我在div中选择第一项时,它会将标签包装在_dgx_donate_donor_first_name-error-message div周围。如果我说要选择第二个元素,它将选择input字段。我想用中间的文字。我的jQuery目前是:
$('#dgx-donate-container .text-input-section').each(function(){
var c = 'text'+$(this).find('input[type="text"]').attr('name');
$(this).find('input[type="text"]').attr('id', c).addClass('text-box');
$(this).find(':first-child:not(#donation_header)').next().wrap('<label for="'+c+'" />');
});不漂亮,但到目前为止似乎很管用。(我想我也需要更改ID,但由于我只是为了造型的目的而使用标签,所以我认为我现在应该没事。)
关于我如何选择文本,有什么建议吗?每个字段的格式与此字段完全相同。
发布于 2015-06-23 16:48:29
$(function(){
var div = $("#_dgx_donate_donor_first_name");
var txt = $.trim(div.text());
var txtNodes = div.contents().filter(function(){
return this.nodeType === 3;
}).remove();
//console.log(txtNodes);
//div.text(""); //don't do this, it will empty your div
var input = div.find("input");
var name = input.attr("name");
var lbl = $("<label for='" + name + "'>" + txt + "</label>");
lbl.insertBefore(input);
});小提琴手例子
发布于 2015-06-23 16:53:44
使用wrapInner,然后重新添加其他节点:
$('#dgx-donate-container .text-input-section').each(function(){
var c = 'text'+$(this).find('input[type="text"]').attr('name');
$(this).find('input[type="text"]').attr('id', c).addClass('text-box');
firstDiv = $(this).children('div:first');
input = $(this).children('input');
$(this).wrapInner('<label for="'+c+'" />')
.prepend(firstDiv)
.append(input);
});示例Fiddle
https://stackoverflow.com/questions/31007757
复制相似问题