jQuery用子元素改变变量

jQuery change variables with child elements

本文关键字:改变 变量 元素 jQuery      更新时间:2023-09-26

我试图在jQuery中针对子元素,根据是否有任何输入进行更改。然而,这段代码有一些问题。首先,即使我指定了文本区域,点击的CSS效果也不会应用到文本区域。

第二,填充输入字段仍然返回变量truth为false,因此它不会执行$('p').html('Solid')下面的代码。

我的HTML:

<div id="section">
    <button>Click It</button>
    <label>
        <input type="text" required="true" />
    </label>
    <label>
        <input type="text" />
    </label>
    <textarea required="true"></textarea>
</div>
<p></p>
$('button').click(function(){
    var truth = true;
    $('#section label').each(function(){
        var chooseinputs = $(this).find('input[required=true], textarea[required=true]');
        if ( !$.trim(chooseinputs.val()) ){
            $(chooseinputs).css('border', '1px solid red');
            $('p').html("Empty");
            truth = false;
        }
        if (truth)
            $('p').html("Solid!");
    });
});

JSFiddle

你只是检查第一个输入,你需要一个foreach

$('button').click(function() {
  var truth = true;
  $('#section label> input[required=true], textarea[required=true]').each(function() {
    
    if (!$.trim($(this).val())) {
      $(this).css('border', '1px solid red');
      $('p').html("Empty");
      truth = false;
    }
    if (truth) {
      $('p').html("Solid!");
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="section">
  <button>Click It</button>
  <label>
    <input type="text" required="true" />
  </label>
  <label>
    <input type="text" />
  </label>
  <textarea required="true"></textarea>
</div>
<p></p>