我试图让 jQuery 在输入文本之前在“未标记”元素上设置标签。但是,它似乎是在上一个标签上设置标签。我无法在代码中手动设置标签,因为它是自动生成的,而且插件开发人员已删除表单字段上的标签。这是我目前拥有的其中一个字段的代码:
<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,但由于我只是将标签用于样式目的,所以我认为我现在应该没问题。)
关于如何选择文本有什么建议吗?每个字段的格式与此完全相同。
最佳答案
$(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);
});
关于jquery - 用标签包装文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31007757/