尝试定位和更改标签文本时遇到了异常困难
<li>
<label></label><br/>
<input type='tel' class='added_phone' name='' value='' maxlength='20' />
</li>
我的变量:
// Phone Inputs
var inputphone = $("<li><label></label><br/><input type='tel' pattern='[0-9]{10}' class='added_phone' name='' value='' autocomplete='off' maxlength='20' /></li>");
该函数检查存在多少个 Phone 对象,然后在页面上创建它们:
$(profileData.phones).each(function(i) {
$('.new_option').append(inputphone);
$('.added_phone').closest('label').text(profileData.phones[0].tag);
$('.added_phone').attr('id', "added_"+profileData.phones[0].tag+"phone" + (i + 1));
});
$('.added_phone').attr('value', profileData.phones[0].label);
});
我能够发现有 1 个或多个电话对象,创建并显示输入,将电话号码放入字段中,但无法定位标签并放入标签(名称) .
尝试了最接近的、父级、标签...代码隧道 X_x
你会如何处理这个问题?
最佳答案
好吧,鉴于您的以下 HTML:
<li>
<label></label><br/>
<input type='tel' class='added_phone' name='' value='' maxlength='20' />
</li>
然后,从输入
中,标签
是:
$(this).parent().find('label');
或者:
$(this).prevAll('label');
请注意,如果任何 li
包含多个 label
/input
,这两种方法都可能返回多个元素。
顺便说一句,您使用的标签
是错误的;它意味着识别文本标签和表单
的输入
(或textarea
或选择
)元素:
This attribute explicitly associates the label being defined with another control. When present, the value of this attribute must be the same as the value of the id attribute of some other control in the same document. When absent, the label being defined is associated with the element's contents.
利用 label
的 for
属性,该属性必须(如果要工作)与 id
属性相同输入
(或类似元素):
<li>
<label for="inputID"></label><br/>
<input id="inputID" type='tel' class='added_phone' name='' value='' maxlength='20' />
</li>
并且,鉴于这种关系,将两者关联起来会变得更容易(假设 this
引用 input
元素):
$('label[for="' + this.id + '"]');
引用文献:
关于jQuery 如何在我的示例中定位标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18453385/