内部.each循环中的jQuery .dialog - 每次迭代都会写入新的对话框内容div - 如何在每个循环中销毁旧的div?

时间:2015-03-06 02:55:59

标签: javascript jquery html css ajax

我有一个使用ajax GET下载xml文件的网页,然后一个函数(xmlParser)在.each循环中解析xml文件。在同一个.each循环中,我正在创建jQuery对话框。

上面提到的ajax GET每1秒重新运行一次,因为它获取的xml文件是动态的。页面上的所有内容都能正常工作(即所有内容都能正常显示和运行),但是当我查看Chrome开发人员控制台中的Elements页面时,我注意到每次ajax函数循环时都会重新创建对话框内容的div,这最终会导致崩溃的页面。

我该怎样防止这种情况?我似乎无法找到一种方法来正确覆盖这些div,以阻止每次创建新的。

我真的很感激别人的帮助。

完整代码如下:

<!DOCTYPE html>
<!--[if IE 8]>
<html class="ie ie8">
  <![endif]-->
  <!--[if IE 9]>
  <html class="ie ie9">
    <![endif]-->
    <!--[if gt IE 9]>
    <!-->
    <html>
      <!--<![endif]-->
<head>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <title>Page Title</title>
      <link rel='stylesheet' id='jquery-ui-theme-css'  href='css1.css' type='text/css' media='all' />
      <link rel='stylesheet' id='googlefonts-css'  href='css2.css' type='text/css' media='all' />
      <link rel='stylesheet' id='bootstrap-css'  href='css3.css' />
      <link rel='stylesheet' id='fontawesome-css'  href='css4.css' type='text/css' media='all' />
      <link rel='stylesheet' id='main-css'  href='css5.css' media='all' />
      <link rel='stylesheet' id='red-css'  href='css6.css' type='text/css' media='all' />
      <link rel='stylesheet' id='responsive-css'  href='css7.css' type='text/css' media='all' />
      <script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
      <script src="//code.jquery.com/ui/1.11.3/jquery-ui.js"></script>
<script>
$(document).ready(function () {
setInterval("ajaxd()", 1000);
});
function ajaxd() {
    "use strict";
    $.ajax({
        type: "GET",
        url: "output.xml",
        dataType: "xml",
        cache: false,
        success: xmlParser
    });
};
function xmlParser(xml) {
    "use strict";
    $(".main2").empty();
    //$(".main").html(''); //blank out appended info on each load

    $('#load').hide();
    var count = 1;
    $(xml).find("proc").each(function () {
        var ip = $(this).find("ip").text();
        var hdBlackGain = $(this).find("hdBlackGain").text();
        var hdLumaGain = $(this).find("hdLumaGain").text();
        var hdChromaGain = $(this).find("hdChromaGain").text();
        var hdHue = $(this).find("hdHue").text();
        var machineName = $(this).find("machineName").text();

        if (hdBlackGain === '0' && hdLumaGain === '0' && hdChromaGain === '0' && hdHue === '0') {
        } else {
            $(".main2").append('<div class="proc"><div class="title"><div class="dialog_but">' + machineName + '</div><div class="dialog_content"><ul><li>Black Gain: ' + hdBlackGain + '</li><li>Luma Gain: ' + hdLumaGain + '</li><li>Chroma Gain: ' + hdChromaGain + '</li><li>Hue: ' + hdHue + '</li><li>IP Address: ' + ip + '</li></ul></div></div></div>');
            $(".proc").show();

        //loop through every button anchor element
        $('.dialog_but').each(function() {

            //create a local scope of a dialog variable to attach
            var $dialog;

            //create the dialog for the div.dialog_content standing next to the anchor element
            //we make the autoOpen false so that it can be reusable
            //also we set the modal = true to appear the dialog as a modal prompt
            $dialog = $(this).next('div.dialog_content').dialog({
              modal: true,
              autoOpen: false,
              width: 600,
              title: 'Current Proc Status: ' + machineName,
              buttons: [
    {
      text: "OK",
      click: function() {
        $( this ).dialog( "close" );
      }
    }
  ]
            });

            //now attach the open even of the dialog to the anchor element
            $(this).click(function(e) {
                //prevent the anchor element to go to the hyperlinked page
                e.preventDefault();

                //open the dialog
                $dialog.dialog('open');
            });
        });
            count = count + 1;
        }
    });
};
</script>
<style> 
.main2{
width:1150px;
margin:0 auto;
height:130px;
}

.proc{
width:208px;
float:left;
margin:10px;
border:1px #dedede solid;
padding:5px;
display:none;
background-color:#A0492E;
}

.title{
text-align:center;
color:#ffffff;
}
</style>
</head>
<body class="boxed home-3">
      <div class="wrap">
        <!-- Header Start -->
        <header id="header">
          <!-- Main Header Start -->
          <div class="main-header">
            <div class="container">
              <!-- TopNav Start -->
              <div class="topnav navbar-header">
                <a class="navbar-toggle down-button" data-toggle="collapse" data-target=".slidedown"> <i class="fa fa-angle-down icon-current"></i>
                </a>
              </div>
              <!-- TopNav End -->
              <!-- Logo Start -->
              <div class="logo pull-left">
                <h1>
                  <a href="http://bcceng">
                    <img src="http://bcceng/wp-content/themes/opseng/img/logo.png" alt="Text goes here" width="222" height="32" style="vertical-align: baseline !important;"></a>
                </h1>
              </div>
              <!-- Logo End --> </div>
          </div></header>
          <!-- Main Header End -->
          <!-- Content Start -->
          <div id="main">
            <!-- Slogan Start-->
            <div class="slogan bottom-pad-small">
              <div class="container">
                <div class="row">
                  <div class="slogan-content">
                    <div class="col-lg-12 col-md-12">
                      <h2 class="slogan-title">Text goes here</h2>
                    </div>
                    <div class="clearfix"></div>
                  </div>
                </div>
              </div>
            </div>
            <!-- Slogan End-->
            <!-- Main Content start-->
            <div class="main-content">
              <div class="container">
                <div class="row">
                  <div align="center">Text goes here</div>
                </div>
              </div>
              <div class="row">
                <div class="main2">
                  <div align="center" class="loader">
                    <img src="loader.gif" id="load" alt="Please wait..." width="16" height="11" align="absmiddle"/>
                  </div>
                </div>
                <div class="clear"></div>
              </div>
              <div class="row">
                <p>
                  <br>
                  <br></p>
              </div>
            </div>
          </div>
          <div class="footer-top">
            <div class="container">
              <div class="row">
                <ul>
                <li>
                  <p>Last updated: 3/4/15 11:34pm</p>
                </li>            
              </ul>
              </div>
            </div>
          </div>
          <!-- Main Content end--> </div>
        <!-- Content End -->
        <!-- Footer Start -->
        <footer id="footer"></footer>
      <!-- Wrap End -->
</body>
    </html>

2 个答案:

答案 0 :(得分:1)

创建对话框对象时,有些元素会添加到正文中但不在容器main2下面,因此调用$(".main2").empty()不会删除它们。

在您的情况下,因为为元素dialog_content创建了对话框,您可以调用destroy methoddialog来删除它们

$('.dialog_content').dialog('destroy');
$(".main2").empty();

另一个选择是使用单个对话框,如

将以下html添加到您的身体

<div class="dialog_content">
    <ul>
        <li>Black Gain: <span class="hd-black-gain"></span></li>
        <li>Luma Gain: <span class="hd-luma-gain"></span></li>
        <li>Chroma Gain: <span class="hd-chroma-gain"></span></li>
        <li>Hue: <span class="hd-hue"></span></li>
        <li>IP Address: <span class="ip"></span></li>
    </ul>
</div>

然后

$(document).ready(function () {
    setInterval("ajaxd()", 1000);

    var $dialog = $('.dialog_content').dialog({
        modal: true,
        autoOpen: false,
        width: 600,
        title: 'Current Proc Status: ',
        buttons: [{
            text: "OK",
            click: function () {
                $(this).dialog("close");
            }
        }]
    });

    $('.main2').on('click', '.dialog_but', function (e) {
        var $this = $(this),
            data = $this.data();
        e.preventDefault();

        $dialog.dialog('option', 'title', 'Current Proc Status: ' + data.machineName);
        $dialog.find('.hd-black-gain').text(data.hdBlackGain);
        $dialog.find('.hd-luma-gain').text(data.hdLumaGain);
        $dialog.find('.hd-chroma-gain').text(data.hdChromaGain);
        $dialog.find('.hd-hue').text(data.hdHue);
        $dialog.find('.ip').text(data.ip);

        //open the dialog
        $dialog.dialog('open');
    })
});

function ajaxd() {
    "use strict";
    $.ajax({
        type: "GET",
        url: "output.xml",
        dataType: "xml",
        cache: false,
        success: xmlParser
    });
};

function xmlParser(xml) {
    "use strict";
    $(".main2").empty();
    //$(".main").html(''); //blank out appended info on each load

    $('#load').hide();
    var count = 1;
    $(xml).find("proc").each(function () {
        var ip = $(this).find("ip").text();
        var hdBlackGain = $(this).find("hdBlackGain").text();
        var hdLumaGain = $(this).find("hdLumaGain").text();
        var hdChromaGain = $(this).find("hdChromaGain").text();
        var hdHue = $(this).find("hdHue").text();
        var machineName = $(this).find("machineName").text();

        if (hdBlackGain === '0' && hdLumaGain === '0' && hdChromaGain === '0' && hdHue === '0') {} else {
            var $proc = $('<div class="proc"><div class="title"><div class="dialog_but">' + machineName + '</div></div></div>').appendTo(".main2");
            $proc.find('.dialog_but').data({
                machineName: machineName,
                hdBlackGain: hdBlackGain,
                hdLumaGain: hdLumaGain,
                hdChromaGain: hdChromaGain,
                hdHue: hdHue,
                ip: ip
            })

            count = count + 1;
        }
    });
};

答案 1 :(得分:1)

由于你的html对我的生命周期很短,因此有必要不增加创建一堆对话和事件处理程序的额外开销,这些对话和事件处理程序的使用可能性非常低。

回收一个对话框非常容易

您可以在要点击的元素上添加title属性,并根据需要提取html。


向页面添加永久对话框:

<div id="dialog">

$('#dialog').dialog({ /* your options*/});

修改xml解析代码中的html字符串:

<div class="dialog_but" title="Current Proc Status: ' + machineName+'">

然后,对于您的点击处理程序,您可以将其放入页面加载代码并将其从xml解析器中删除

$(document).on('click','.dialog_but',function(){
     var title = this.title,
         content = $(this).next('div.dialog_content').html();
     $('#dialog').html(content).dialog('option','title', title).dialog('open');
});

一个额外的步骤是添加一个css规则来隐藏.proc .dialog_content

CSS

.proc .dialog_content{display:none}