我有一个带有以下错误消息的表单。此错误消息正常运行,所以我首先分享它,然后展示我接下来要更改的内容:
if (thing is true) {
$(this).parents("table:first")
.prop("disabled",true)
.css({'background-color' : 'lightgray'})
.after("<font color = red id=error3><strong>*</strong> Please check that your start and end dates are between June 15, 2018 and November 30, 2019. The Start Date may not be greater than the End Date.</font>");
}
我想将错误消息更改为在表单的前面包含用户提供的日期。当我使用连接时,它看起来像这样:
if (thing is true) {
// example dates provided by user
cysd = $("#id_currentyearstartdate").val();
cyed = $("#id_currentyearenddate").val();
// let's say cysd is January 1, 2018 and cyed is December 31, 2018
$("input#next-submit-button")
.prop("disabled",true)
.css({'background-color' : 'lightgray'})
.after("<font color = red id=error2><br>Please resolve any errors above before continuing. <br><strong>*</strong> Check that your start and end dates are between </font>" + cysd + "<font color = red id=error2> and </font>" + cyed + "<font color = red id=error2>. The Start Date may not be greater than the End Date.</font>");
我搞砸的地方是,在原始错误消息中,我有一条字体 ID 为“error2”的错误消息。这使我能够在正确的条件下轻松添加或删除错误消息。
我不知道如何在实际的错误消息文本或字体标签中包含变量值,因此当 id=error2 时仍会引用整个 string "请检查您的开始日期和结束日期是否在 2018 年 1 月 1 日和 2018 年 12 月 31 日之间。开始日期不得大于结束日期。
最佳答案
把它放在同一个标签里...
.after("<font color = red id=error2><br>Please resolve any errors above before continuing. <br><strong>*</strong> Check that your start and end dates are between " + cysd + ". The Start Date may not be greater than the End Date.</font>");
您也可以使用 template literals而不是 concating 这更容易一些,因为您不必担心混淆您的报价。用反引号 (`) 包裹您的字符串,并将您的变量放在以 $
开头的 curl 中。
.after(`<font color = red id=error2><br>Please resolve any errors above before continuing. <br><strong>*</strong> Check that your start and end dates are between ${cysd}. The Start Date may not be greater than the End Date.</font>`);
无论如何,您都不应该使用font
标签- they're obsolete .请改用 css 和 span 标签。
.after(`<span style=color:red id=error2><br>Please resolve any errors above before continuing. <br><strong>*</strong> Check that your start and end dates are between ${cysd}. The Start Date may not be greater than the End Date.</span>`);
关于javascript - 如何将 JS 变量添加到错误消息中并保留一个字体 ID 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48466675/