即使内在价值不对,也不要尊重

时间:2017-04-06 18:38:40

标签: javascript jquery if-statement dom

这是我的HTML代码:



$(function() {
  function reverse(s) {
    return s.split("").reverse().join("");
  }

  $('button').click(function() {
    var span = $(this).siblings('span');
    span.text(function() {
      var reversed = reverse($(this).text());
      return reversed;
    });

    if (!span.children('small').length) {
      span.wrapInner('<small></small>');
      console.log(!span.children('small').length);
    }
  });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<span>reverse1</span>
<span>reverse2</span>
<button>reverse me</button>
&#13;
&#13;
&#13;

我把一个console.log放到if语句中,只在DOM中添加一个小的(不确定wrapInner函数)检查是否只添加了一个小节点。我检查了逻辑表达式中的值是真的,其中没有小标签,并且当它被添加时为假。谁能帮助我理解?

1 个答案:

答案 0 :(得分:1)

我已经更新了我的代码,以便在您的范围内创建一个小的,如果不存在,并将跨度的文本内容放在那个小的范围内。它只创造了一个小的第一通道。所有后续通行证只需清空小部件并重新填充。我真的不需要在IF语句中清空小的,只是证明你可以用它来处理它。

$(function() {
  function reverse(s) {
    return s.split("").reverse().join("");
  }
  // When the button el is clicked, reverse
  $('button').click(function() {
    var span = $(this).siblings('span');

    span.each(function() {
      // Store the text string, regardless of DOM
      var textStr = $(this).text();

      if (!$(this).children("small").length) {
        // I don't have a nested small. Make one!
        //  Note that, in making one, I wipe out any
        //  content in this span element.
        console.log("No small!");
        $(this).html("<small></small");
      } else {
        // I have a small. Don't wipe the entire contents
        //   of this span, simply empty the small.
        console.log("Has small!");
        $(this).children("small").empty();
      };
      
      // Either way, I now have a span with an empty small.
      //  Stick my text in there!
      $(this).children("small").text(reverse(textStr));
    });

  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <span>reverse1</span>
  <span>reverse2</span>
  <button>reverse me</button>
</div>