【问题标题】:Changing DOM elements with Jquery使用 Jquery 更改 DOM 元素
【发布时间】:2015-03-25 09:49:48
【问题描述】:

我有一个如下所示的引导面板:

  <div class="col-md-4 col-sm-6">
            <div class="panel panel-default ">
                <div class="panel-heading"><a href="#" class="pull-right" id="back">Back</a> <h4>Title 1</h4>
                </div>
                <div class="panel-body pre-scrollable">
                    <div id="data">
                        <div id="info">
                            <div class="list">Item 1
                                <div class="hidden">This is the rest of the data</div>
                            </div>
                            <div class="list">Item 2
                                <div class="hidden">This is the rest of the data</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>    

我正在使用这个 javascript 在列表项和子 div 之间切换并在面板中显示内容。单击“返回”链接时,面板会显示原始项目列表。

 $(document).on("ready", function(){/* jQuery toggle layout */

   $( "#info .list" ).on('click' , function() {
     window.data = $("#info").html();
     var htmlString = $( this ).find('div.hidden').html();

     $( "#info" ).html( htmlString );

   });

   $( "#back" ).on('click',  function() {
     console.log(window.data);
     $( "#info" ).html( window.data ); 
   });
 });

一切正常,只是它只能工作一次,然后我必须刷新页面才能再次工作。

我在这里错过了什么?

这是一个工作示例:

http://www.bootply.com/y84ZiHTQ5W

【问题讨论】:

  • 什么 $(document).ready();在点击事件中做什么?
  • 那是我在试验 - 更新

标签: javascript jquery twitter-bootstrap-3 panel


【解决方案1】:

当您使用 javascript 操作 dom 时,该事件只会工作一次。即使被js改变了也要在元素上绑定click事件,你应该使用事件委托技术,它的语法有点相同:

    $("#info").on('click', ".list", function() {
      window.data = $("#info").html();
      var htmlString = $(this).find('div.hidden').html();

      $("#info").html(htmlString);
    });

    $(document).on("click","#back", function() {
      console.log(window.data);
      $("#info").html(window.data);
    });

您也可以将$("#info") 更改为:$(document), $("body")

【讨论】:

  • 谢谢你——成功了。虽然,我确信尝试过:)
【解决方案2】:

它只在第一次起作用的原因是,当您设置#info div 的 html 内容时,与它关联的点击事件的 DOM 元素会被覆盖。

要让它工作,您需要在编写 #info div 的内容后重新添加 click 事件处理程序。像这样的:

$( "#info .list" ).on('click' , clickHandler);

function clickHandler() {
   window.data = $("#info").html();
   var htmlString = $( this ).find('div.hidden').html();

   $( "#info" ).html( htmlString );
   $( "#info .list" ).on('click' , clickHandler);
}

【讨论】:

    猜你喜欢
    • 2016-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-27
    • 2017-05-03
    • 1970-01-01
    • 2010-09-25
    • 2013-12-03
    相关资源
    最近更新 更多