【问题标题】:Append on first click and detach on second button click在第一次单击时附加并在第二次按钮单击时分离
【发布时间】:2018-09-05 16:10:53
【问题描述】:

我有这个 Jquery 函数,在第一次单击按钮时它正在分离 #mainFTL,在第二次单击时它正在附加它,但我希望该函数执行相反的操作。第一次单击附加第二次单击分离。谢谢。

<button type="button" name="mainFTLbutton" id="mainFTLbutton" class="btn btn-success btn-block">FTL - Full Truckload</button>

$(document).ready(function() {
      var p;

      $('#mainFTLbutton').click(function() {

        $('#mainFTL').show();
        if (p) {
          p.appendTo('.appendFTL');
          p = null;

        } else {
          p = $('#mainFTL').detach();
        }
      });
    });

【问题讨论】:

  • 然后交换函数?

标签: jquery function append detach


【解决方案1】:

试试这个:

$(document).ready(function() {
  // cache your selectors
  var main = $('#mainFTL'),
      btn = $('#mainFTLbutton');
  
  btn.click(function(){
    // check if the element is visible (it will only be visible when appended)
    if(main.is(':visible')){
      main.detach();
    }else{
      main.appendTo('.appendFTL').show();
    }
  });
});
#mainFTL {
 display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="mainFTL">Hello</div>

<div class="appendFTL"></div>

<button type="button" name="mainFTLbutton" id="mainFTLbutton" class="btn btn-success btn-block">FTL - Full Truckload</button>

【讨论】:

  • 非常感谢,这正是我想要的。
【解决方案2】:

然后只需查找元素并设置变量。

var p = $('#mainFTL').detach();

然后 p 将在第一次单击时存在并附加它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多