JQuery,动态添加div并显示错误信息



我从验证api获得以下json响应,第一个属性是带有错误消息的每个输入字段的id。

{
"backgroundcolor": "Color is not Supported",
"terms" : "Sorry the Terms are blank"
}

我正在使用jquery和bootstrap,并希望在该特定id的每个输入字段之后附加下面的html。可以动态添加div吗?

<div id="backgroundcolor" class="invalid-feedback">
Color is not Supported
</div>

:

<div class="col-md-6">
<input type="text" class="form-control is-invalid" id="backgroundcolor" aria-describedby="validationServer03Feedback" required>
</div> 

:后

<div class="col-md-6">
<input type="text" class="form-control is-invalid" id="backgroundcolor" aria-describedby="validationServer03Feedback" required>
<div id="backgroundcolorFeedBack" class="invalid-feedback">
Color is not Supported.
</div>

JavaScript单独是最好和最快的解决方案,所以这里是我将如何做到的:

let response = JSON.parse(response);
let fragment = document.createDocumentFragment()
let child = document.createElement('div');
child.id = Object.keys(response)[0] + 'FeedBack';
child.className = 'invalid-feedback';
child.innerText = Object.values(response)[0];
fragment.appendChild(child);
document.getElementById(Object.keys(response)[0]).after(fragment);

我希望这对你有帮助。

注意:createDocumentFragment()可能比单独的createElement略快,但这不是必需的。

编辑:你也可以检查是否已经有div错误,这将防止重复的div

if(!document.getElementById(Object.keys(response)[0].length) {
// Here goes code from above
}

相关内容

最新更新