0

我有大约 20 个表单文本输入。对于它们中的每一个,我想确保它们存在并对它们应用相同的逻辑,如下所示:

var title = $('#title')
if (title == '') {
     title.css({
       'background-color': 'rgba(230, 89, 78, 0.07)',
    }); 
};

<input type="text" id="title" />

我将如何“批量”应用这个,而不是为我拥有的每个文本输入重写这个?理想情况下,我希望有一个变量列表,其中包含我需要执行此操作的所有字段:['title', 'company', 'copyright', ...].

4

2 回答 2

1

您可以给他们一个通用类(如validate),然后使用.each()

$('.validate').each(function() {
    var $this = $(this);

    if (!$this.val()) {
        $this.removeClass('valid');
        $this.addClass('invalid');
    } else {
        $this.removeClass('invalid');
        $this.addClass('valid');
    }
});

从那里,使用 CSS 应用样式。

于 2013-01-11T00:41:22.550 回答
0

$("#title").css() 将枚举每个元素,但是,id 在每个页面上都是唯一的。我建议添加一个类 'title' 并改为通过 $(".title").css() 查询。

<input id="title1" class="title" />
<input id="title2" class="title" />
<input id="title3" class="title" />

<script type="javascript">
  $(".title")each(function(){
      if(!$(this).val()){
        $(this).css({
          'background-color': 'rgba(230, 89, 78, 0.07)',
        }); 
      }
  });
</script>
于 2013-01-11T00:40:29.527 回答