如何在选中的文本框下面写文字?

时间:2017-09-12 09:51:25

标签: javascript jquery html

这是我的HTML和jQuery代码。代码工作正常,但问题是当我点击一个复选框时,文本"完成"在所有复选框下面变得可见,而不是仅在那个复选框。

我的HTML代码是:



$('.label__checkbox').click(function() {
  if ($(".label__checkbox").is(':checked')) {
    $(".finish").css("display", "block");
  } else {
    $(".finish").css("display", "none");
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="center">
  <label class="label">
        <input  class="label__checkbox" type="checkbox" />
        <span class="label__text">
          <span class="label__check">
            <i class="fa fa-check icon"></i>
          </span>
        </span>
      </label>
  <span class="finish">FINISHED</span>
</div>
<div class="center">
  <label class="label">
        <input  class="label__checkbox" type="checkbox" />
        <span class="label__text">
          <span class="label__check">
            <i class="fa fa-check icon"></i>
          </span>
        </span>
      </label>
  <span class="finish">FINISHED</span>
</div>
<div class="center">
  <label class="label">
        <input  class="label__checkbox" type="checkbox" />
        <span class="label__text">
          <span class="label__check">
            <i class="fa fa-check icon"></i>
          </span>
        </span>
      </label>
  <span class="finish">FINISHED</span>
</div>
<div class="center">
  <label class="label">
        <input  class="label__checkbox" type="checkbox" />
        <span class="label__text">
          <span class="label__check">
            <i class="fa fa-check icon"></i>
          </span>
        </span>
      </label>
  <span class="finish">FINISHED</span>
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:3)

您可以使用DOM遍历方法在当前元素上下文中定位它们,即this

.closest()可用于遍历label,然后使用.next()定位<span>

$('.label__checkbox').change(function() {
  var finish = $(this).closest('.label').next(".finish");
  //var finish = $(this).closest('.center').find(".finish");
  if ($(this).is(':checked')) {
    finish.css("display", "block");
  } else {
    finish.css("display", "none");
  }
}).trigger('change');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="center">
  <label class="label">
    <input  class="label__checkbox" type="checkbox" />
    <span class="label__text">
      <span class="label__check">
        <i class="fa fa-check icon"></i>
      </span>
    </span>
  </label>
  <span class="finish">FINISHED</span>
</div>
<div class="center">
  <label class="label">
    <input  class="label__checkbox" type="checkbox" />
    <span class="label__text">
      <span class="label__check">
        <i class="fa fa-check icon"></i>
      </span>
    </span>
  </label>
  <span class="finish">FINISHED</span>
</div>