gpt4 book ai didi

javascript - 按下按钮后如何重置错误消息?

转载 作者:行者123 更新时间:2023-12-01 02:48:45 25 4
gpt4 key购买 nike

我目前正在学习 JavaScript,并且正在开发一个模拟宠物收养网站。 super 简单的布局和功能,除了一个问题。当按下“提交”按钮并且用户尝试提交宠物以供收养而不单击“条款和条件”框时,我收到一条错误消息。出现错误,但如果我再次单击该按钮(没有选中条款和条件复选框),就像该错误只是附加了另一条错误消息。

我正在尝试将其放在不会创建另一个错误消息的地方。我尝试在函数末尾将alertMessage变量设置为空字符串,希望它能够自行重置,但这不起作用。

预先感谢您的所有帮助。

$('#add-pet').on('click', function() {

if (termsBox.checked) {
// Grab info from the form
let $name = $('#pet-name');
let $species = $('#pet-species');
let $notes = $('#pet-notes');

// Assemble the HTML of our new element with the above variables
let $newPet = $(
'<section class="six columns"><div class="card"><p><strong>Name:</strong> ' + $name.val() +
'</p><p><strong>Species:</strong> ' + $species.val() +
'</p><p><strong>Notes:</strong> ' + $notes.val() +
'</p><span class="close">&times;</span></div></section>'
);
// Attach the element to the page
$('#posted-pets').append($newPet);

// Make the 'x' in the corner remove the section it's contained within
$('.close').on('click', function() {
$(this).parents('section').remove();
});

// Reset form fields
$name.val('');
$species.val('Dog');
$notes.val('');

} else {
let br = document.createElement('BR');
let alertMessage = document.createTextNode('Please read the terms and conditions.');
let span = document.createElement('SPAN');
span.style.color = '#FF0000';
span.appendChild(alertMessage);
let termsLabel = document.getElementById('termsLabel');
termsLabel.appendChild(br);
termsLabel.appendChild(span);
alertMessage = '';
}
});

最佳答案

最简单的方法是使用 innerHTML DOM 元素属性来清理节点的内容:

else {
let br = document.createElement('BR');
let alertMessage = document.createTextNode('Please read the terms and conditions.');
let span = document.createElement('SPAN');
span.style.color = '#FF0000';
span.appendChild(alertMessage);
let termsLabel = document.getElementById('termsLabel');
termsLabel.innerHTML = ''; // this removes previous content of the node including all it's children
termsLabel.appendChild(br);
termsLabel.appendChild(span);
}

但我只会使用:

else {
let termsLabel = document.getElementById('termsLabel');
termsLabel.innerHTML = 'Please read the terms and conditions.';
}

并且 termsLabel 元素的所有样式都应该通过 CSS 以类似的方式声明

#termsLabel {
margin-top: 15px;
color: red;
}

UPD 这是满足新要求的 fiddler:https://jsfiddle.net/yy1z75e7/2/

关于javascript - 按下按钮后如何重置错误消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47105958/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com