0

js:

var KEYS = {
    SPACE: 32
};
$(".trim-space").keyup(function (e) {
    var $this = $(this);
    $this.val($.trim($this.val()));
    if (e.keyCode == KEYS.SPACE) {
        $(".errorlist").show();
        $(".errorlist").text("No space please");
    }
});

我的html:

<tr>
    <td>Daytime phone:</td>
    <td>
        <input type="text" class="trim-space" name="phone_daytime" />
        <div style="display:none" class="errorlist">No space please</div>
    </td>
</tr>
<tr>
    <td>Mobile phone:</td>
    <td>
        <input type="text" class="trim-space" name="phone_mobile" />
        <div style="display:none" class="errorlist">No space please</div>
    </td>
</tr>

在我的应用程序中,有六个具有相同类名的字段来验证空间。我通过隐藏的 div 显示错误消息,它也具有相同的类。这些 div 位于表的<td>标签内。

我的问题是,如果我按下空格键,它会显示错误消息,但它会显示在所有 div 中。我想显示空格键按下的输入字段的错误消息。如何执行此操作。

4

4 回答 4

1

尝试这个:

$this.siblings(".errorlist").text("No space please").show();

请参阅文档jQuery.siblings()

于 2013-09-02T07:54:12.253 回答
1

使用 .closest 仅显示壁橱 div。

$this.closest($(".errorlist")).show();
$this.closest($(".errorlist")).text("No space please");
于 2013-09-02T07:43:55.610 回答
0

利用

var KEYS = { SPACE: 32 };
    $(".trim-space").keyup(function(e) {
       var $this = $(this);
       $this.val($.trim($this.val()));

      if (e.keyCode == KEYS.SPACE) {

          $this.next(".errorlist").text("No space please").show(); 
     }
     else{

          $this.next(".errorlist").hide();
     }
 });
于 2013-09-02T07:53:49.940 回答
0

为每个元素设置 ID,因为 ID 用于标识页面上的唯一元素:

<div style="display:none" id="nameField" class="errorlist">No space please</div>

接着:

$("#nameField").text("No space please"); 
于 2013-09-02T07:45:54.597 回答