jQuery 如何在我的示例中定位标签

标签 jquery text label

尝试定位和更改标签文本时遇到了异常困难

<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);
});

enter image description here

我能够发现有 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.

利用 labelfor 属性,该属性必须(如果要工作)与 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/

相关文章:

javascript - 如何在 ASP.Net MVC 4 中为日期选择器添加 javascript

c++ - 将基本文本添加到 Win32 应用程序,c++

linux - 即时修改数据流

jquery - 在加载时替换表格标签文本

angular - 是否可以根据条件更改 Angular 中按钮的标签?

javascript - 网页上的语法高亮 Markdown

jquery - SelectBoxIt 与 CSS 文件冲突

jquery - ajax提交后,滚动到表单顶部

css - 悬停时按钮颜色不变

javascript - 使用javascript获取一个asp.net Label控件