javascript - 如何将 JS 变量添加到错误消息中并保留一个字体 ID 标签

标签 javascript jquery html css

我有一个带有以下错误消息的表单。此错误消息正常运行,所以我首先分享它,然后展示我接下来要更改的内容:

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/

相关文章:

javascript - 使用 getter 在 React 组件中渲染另一个组件是一种好习惯吗?

javascript - 从下拉列表中选择多个值并调用 javaScript 函数

html - 为什么我的文本对齐和垂直对齐不适用于图像?

php - 在特定区域适配 HTML 表格

javascript - 页面刷新后保持最后一个复选框处于选中状态

javascript - 如何在 AVA 上使用 @decorator (redux-connect) 测试组件 undecorator?

javascript - Internet Explorer 7 折叠空跨度上的空白区域,如何防止这种情况发生?

javascript - 一种从不在 Provider 内部的组件修改 redux 存储的方法?

php 即时搜索崩溃

javascript - 在 Angular JS 中必须至少选择一个复选框吗?我没有得到完美的答案,我们该如何做到这一点?