如何让jQuery只选择FIRST nearest()元素?

时间:2014-03-02 00:22:23

标签: javascript jquery html css

HTML

<h5>Do you have a reference number?</h5>
  <span class="form-mini-style has_sub_span_field"> <input type="radio" value="1" name="ref">Yes </span>
  <span class="form-mini-style has_sub_span_field"> <input type="radio" value="0" name="ref">no </span> </span>
  <span class="sub_span" style="display:none;">
    <h5>Reference Number:</h5> --- FIELD HERE --- </span>

<h5>Other questions . . . 1 </h5>
  <span class="form-mini-style"> <input type="radio" value="1" name="oq1">Yes </span>
  <span class="form-mini-style"> <input type="radio" value="0" name="oq1">no </span> </span>
  <!-- no sub_span -->

<h5>Other questions . . . 2 </h5>
  <span class="form-mini-style"> <input type="radio" value="1" name="oq2">Yes </span>
  <span class="form-mini-style"> <input type="radio" value="0" name="oq2">no </span> </span>    
  <!-- no sub_span -->

<h5>Do you like TacoBell?</h5>
  <span class="form-mini-style has_sub_span_field"> <input type="radio" value="1" name="tacobell">Yes </span>
  <span class="form-mini-style has_sub_span_field"> <input type="radio" value="0" name="tacobell">no </span> </span>
  <span class="sub_span" style="display:none;">
    <h5>Taco Bell Favorite Foods:</h5> --- FIELD HERE --- </span>

的jQuery

$(function () {
  $("input", ".has_sub_span_field").on('click', function () {
  var next_span_class, next_span_value;
    next_span_class = $(this).parent().next().attr('class');
    next_span_value = $(this).val();

    if (next_span_class != 'sub_span') {
      next_span_class = $(this).parent().next().next().attr('class');
    }

    if (next_span_class == 'sub_span' && next_span_value == 1) {
      $('.' + next_span_class).is(":visible") ? true : $('.' + next_span_class).show();
    } else {
      $('.' + next_span_class).hide();
    }
  });
});

我想要做的只是show sub_span所选的广播输入为closest这是一个小提琴:{{3 }}

上述代码的问题是,单击单选按钮时会显示全部 sub_span,无论单击单选按钮的距离如何。

1 个答案:

答案 0 :(得分:3)

代码按类选择元素:

$('.' + next_span_class)

所以这正是你得到的。当你可以简单地遍历DOM并“直接”走向你想要显示/隐藏的元素时,为什么要经历所有的间接?

$(function () {
    $("input", ".has_sub_span_field").on('click', function () {
        var next_span = $(this).parent().nextAll(".sub_span:first");
        var next_span_value = $(this).val();

        if (next_span_value == 1) {
            next_span.show();
        } else {
            next_span.hide();
        }
    });
});

http://jsfiddle.net/mattball/PgrAy/


N.B。而不是让==为你执行类型强制,写这个是更好的风格:

if (parseInt(next_span_value, 10) === 1) {
    ...
}

  

为什么nextAll()而不是nextUntil()

nextUntil()不是主意,因为它会选择多个元素,并且它会停止您实际需要的元素。仔细阅读文档:

  

获取每个元素的所有后续兄弟,但不包括与传递的选择器,DOM节点或jQuery对象匹配的元素。


  

为什么你必须明确地说parent()不应该足够聪明才能走dom直到找到匹配?

这里没有魔力。 jQuery不知道在DOM中的哪个位置,与起始元素相关,你想要搜索。所以你必须明确。