【问题标题】:jquery, to manage the next elementsjquery,管理下一个元素
【发布时间】:2017-12-05 10:03:22
【问题描述】:

我是 jquery 新手,需要您的帮助来解决问题。我正在使用 jQuery Validation 插件来验证我的表单。默认情况下,这个插件的作用是在验证发生时创建一个带有“errorMessage”类的标签。由于输入标签不允许在 CSS 中使用 ::before / ::after,因此要设置我的表单样式,我需要在输入之后立即添加一些 HTML 元素。

问题: 插件会下推该 HTML 标记,以便它可以在输入标记之后立即创建自己的“错误”标签。

发生了什么

<input type="text" name="FirstName" class="inputField required">
<label class="errorMessage">Field is Required</label>
<div class="indicator"></div>

我想要什么

<input type="text" name="FirstName" class="inputField required">
<div class="indicator"></div>
<label class="errorMessage">Field is Required</label>

为了解决这个问题,我尝试了一些代码,但它只是在不同的场景中添加了多个“指标类”

我的脚本

// On Document Ready
// I need this indicator on all inputs by default.
$(".inputField").each(function(i, obj) {
    $(this).after('<div class="indicator"></div>');
});

// On Input Focus Event
$(".inputField").focus(function(){
    if($(this).next().hasClass('errorMessage')) { 
        $(this).after('<div class="indicator"></div>');
    }
});

结果

<input type="text" name="FirstName" class="inputField required">
<div class="indicator"></div>
<label class="errorMessage">Field is Required</label>
<div class="indicator"></div>

如何停止“indicator div”的重复,以及是否有一种聪明的方法可以编写此代码以使其快速呈现。

任何帮助都非常感谢,在此先感谢。

【问题讨论】:

  • 你的indicator div 是干什么用的?

标签: jquery forms validation


【解决方案1】:

您是否考虑过使用errorplacement 回调?

以下内容应采用包含验证错误的输入元素 - element - 并允许您覆盖创建错误通知的位置。

$("#id-of-your-form").validate({
  errorPlacement: function(error, element) {
    error.appendTo(element.next(".indicator"));
  }
});

然后您可以简单地将您的 HTML 保留为:

<input type="text" name="FirstName" class="inputField required">
<div class="indicator"></div>

【讨论】:

  • @timotgyclifford 谢谢朋友,它解决了这个问题。
猜你喜欢
  • 1970-01-01
  • 2010-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多