【问题标题】:Add a label tag for each input tag dynamically for the DOM using JQuery使用 JQuery 为 DOM 动态添加每个输入标签的标签标签
【发布时间】:2014-04-01 00:17:35
【问题描述】:

1.input元素的id属性和对应的label元素应该有for属性。这两个属性的值必须相等。为此,需要使用 JQuery 为 DOM 的每个输入标签添加标签标签。

例子:

First Name :<input type="text" name="first_name" id="firstName" value="" maxlength="100" />

需要补充

<label for="firstName">First Name : <label> 
<input type="text" name="first_name" id="firstName" value="" maxlength="100" />

2。 或者这样也可以

<label> First Name : <input type="text" name="first_name" id="firstName" value="" maxlength="100" /></label>

提前非常感谢你:) :)

【问题讨论】:

    标签: javascript jquery html dom foreach


    【解决方案1】:

    你可以用wrap()点赞

    jQuery(function ($) {
        $('input').wrap(function () {
            return $('<label />', {
                for: this.id
            }).append(this.previousSibling)
        })
    })
    

    演示:Fiddle


    或者用.before()点赞

    jQuery(function ($) {
        $('input').before(function () {
            return $('<label />', {
                for: this.id
            }).append(this.previousSibling)
        })
    })
    

    演示:Fiddle

    【讨论】:

    • 嘿,非常感谢。这是我所期待的。但是当我将您的编码复制粘贴到我的代码中时,它会给出错误:(它会加下划线。M 使用 aptana studio 编写脚本。我需要更改 DOM。
    猜你喜欢
    • 1970-01-01
    • 2015-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多