简体   繁体   English

在另一个元素之后添加HTML元素

[英]Adding an HTML element after another element

I am using the registration form 我正在使用注册表

<form role="form" id="registrationForm">
    <div class="form-group">
        <h2><span th:text="#{register.title}">Create account</span></h2>
    </div>
    <div class="form-group">
       <label class="control-label" for="username" th:text="#{register.yourUsername}">Your username</label>
       <input name="username" id="username" type="text" maxlength="36" class="form-control" th:placeholder="#{register.username}"/>
    </div>
    <div class="form-group">
       <label class="control-label" for="email" th:text="#{register.email}">E-mail</label>
       <input name="email" id="email" type="email" class="form-control" th:placeholder="#{register.email}"/>
    </div>
...

I validate the form on the server and if there is an error then I return a list of errors in the JSON board.Then I try to insert an error message in the appropriate places on the form. 我在服务器上验证表单,如果有错误,则在JSON板中返回错误列表,然后尝试在表单的适当位置插入错误消息。

$.ajax({
        type: 'POST',
        url: '/register',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: JSON.stringify(registerDTO),
        success: function (result) {
            console.log("SUCCESS");
            window.location.replace("/signIn");
        },
        error: function (error) {
            var obj = JSON.parse(error.responseText);
            for(var i = 0; i < obj.field_errors.length; ++i) {
                var objError = obj.field_errors[i];

                if(objError.field === "reCaptcha") {
                    grecaptcha.reset();
                    console.log('error captcha');
                }
                if(objError.field === "username") {
                    $('#username').append('<label id="username-error" class="error" for="username">' + objError.message + '</label>');
                    console.log('error username');
                }
            }
        }
    });

It is a line 这是一条线

$('#username').append('<label id="username-error" class="error" for="username">' + objError.message + '</label>');

How can I add a label after <input name="username" .. /> ? 如何在<input name="username" .. />之后添加标签?

使用.after()吗?

$("input[name='username']").after('<label id="username-error" class="error" for="username">' + objError.message + '</label>');

.after() and .insertAfter() methods will do same will add the DOM. .insertAfter() .after().insertAfter()方法将执行相同操作,将添加DOM。

$(target).after(elementInserted)
$(elementInserted).insertAfter(target)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM