如果已经存在,如何阻止jQuery加载div

时间:2016-01-08 03:23:04

标签: javascript jquery ajax

我为我的网站创建了一个模拟控制台,但是我遇到了一个问题,即无论何时多次提交输入值,jQuery都会重新加载div,因为它标有特定的id。

我不想克隆div,所以我附上一条消息说它已经存在了。我不希望jQuery再次重新加载它,所以我试图想出一个解决方案。

如果已经存在,我如何阻止jQuery加载div?

JSBin

$(document).ready(function() {
    $.ajaxSetup ({
        cache: false
    });

    // Check on keydown
    $('.inputs').keyup(function (e) {
        if (e.keyCode == 13) {

            var value = $(this).val();
            var ajax_load = "<p>LOADING<span class=\"blink\">_</span></p>";

            var loadGlossary = "https://unilogue.github.io/commands/glossary.asp";

            var errorLine = $("<p><span class=\"cmd\">&#62;&nbsp;UNKNOWN COMMAND</span></p><br>");
            var newLine = $('.inputs').clone(true).val('');
            var help = $("<p><span class=\"cmd\"># COMMANDS : [m]ap&nbsp;&nbsp;&nbsp; [d]erive [g]lossary<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;[?] help [clear]&nbsp; [git]</span></p><br>");

            var glossary = $("<div id=\"div3\"></div>");

            // Tiny jQuery Plugin
            // by Chris Goodchild
            $.fn.exists = function(callback) {
                var args = [].slice.call(arguments, 1);

                if (this.length) {
                    callback.call(this, args);
                }

                return this;
            };

            // Usage
            $(glossary).exists(function() {
                this.append('<p><span class=\"cmd\">&#62;&nbsp;[g]lossary is already open!</span></p><br>');
            });

            if (value == 'g') { // If input value is div3
                $('.container').append(glossary);
                $("#div3").html(ajax_load).load(loadGlossary);
                $('.container').append("<p>&#62;&nbsp;</p>").append(newLine);
                $(this).prop('disabled', true);
                $(this).removeClass('inputs');
                $('.inputs').replaceWith(newLine);
                $('.inputs:first').focus();
            } else if (value != '') { // If input value is wrong
                $('.container').append(errorLine);
                $('.container').append("<p>&#62;&nbsp;</p>").append(newLine);
                $(this).prop('disabled', true);
                $(this).removeClass('inputs');
                $('.inputs').replaceWith(newLine);
                $('.inputs:first').focus();
            }
        }
    });
});
<link rel="icon" href="favi.png">
<link rel="stylesheet" href="https://unilogue.github.io/css/style.css">
<script type="text/javascript" src="https://unilogue.github.io/js/jquery-1.11.3.min.js"></script>
<header>
    <div id="prompt">enter the letter 'g' to load the div, notice how it keeps reloading if you enter the letter 'g' again? i don't want that to happen.</div>
    <br>
</header>
<div class="container"><p>&#62;&nbsp;</p><input class="inputs" type="text" placeholder="ENTER COMMAND" /></div>

我可以尝试将加载div的函数组合成一个变量,然后创建一个语句,如果div有.length()我可以.detach().remove()来自函数的变量这样div不再加载?

// Tiny jQuery Plugin
// by Chris Goodchild
$.fn.exists = function(callback) {
    var args = [].slice.call(arguments, 1);

    if (this.length) {
        callback.call(this, args);
    }

    return this;
};

// Usage
$(glossary).exists(function() {
    this.append('<p><span class=\"cmd\">&#62;&nbsp;[g]lossary is already open!</span></p><br>');
});

if (value == 'g') { // If input value is div3
    /* combine these --> */  $('.container').append(glossary);
    /* into one var  --> */  $("#div3").html(ajax_load).load(loadGlossary);
    $('.container').append("<p>&#62;&nbsp;</p>").append(newLine);
    $(this).prop('disabled', true);
    $(this).removeClass('inputs');
    $('.inputs').replaceWith(newLine);
    $('.inputs:first').focus();
}

将最后五行合并为一个变量对于缩短代码长度也很有用,因为我已将它们复制到my script的每个else if语句中。我也认为我可以让jQuery忽略整个if if语句并将最后五行移动到Chris Goodchild的插件中,因为它已经检查div是否存在。

编辑:我能够将这些等效的代码块减少为函数,现在可以对其进行操作。

$(document).ready(function() {

 $.ajaxSetup ({
     cache: false
 });



      // Check on keydown
     $('.inputs').keyup(function (e) {
    		if (e.keyCode == 13) {

           var value = $(this).val();
           var ajax_load = "<p>LOADING<span class=\"blink\">_</span></p>";


          var loadGlossary = "https://unilogue.github.io/commands/glossary.asp";

           var errorLine = $("<p><span class=\"cmd\">&#62;&nbsp;UNKNOWN COMMAND</span></p><br>");
           var newLine = $('.inputs').clone(true).val('');

           var glossary = $("<div id=\"div3\"></div>");
              
          $.fn.gCmd = function() {
             $('.container').append(glossary);
             $("#div3").html(ajax_load).load(loadGlossary);
           };

           $.fn.newLine = function() {
            $('.container').append("<p>&#62;&nbsp;</p>").append(newLine);
            $(this).prop('disabled', true);
            $(this).removeClass('inputs');
            $('.inputs').replaceWith(newLine);
            $('.inputs:first').focus();
           };

          // Tiny jQuery Plugin
          // by Chris Goodchild
          $.fn.exists = function(callback) {
            var args = [].slice.call(arguments, 1);

            if (this.length) {
              callback.call(this, args);
            }

            return this;
          };

          // Usage
          $(glossary).exists(function() {
            // maybe the function to prevent .gCmd() could go here?
            this.append('<p><span class=\"cmd\">&#62;&nbsp;[g]lossary is already open!</span></p><br>');
          });

            if (value == 'g') { // If input value is div3
                $(this).gCmd();
            } else if (value != '') { // If input value is wrong
                $('.container').append(errorLine);
            }
/*appends to all lines */ $(this).newLine();
          }
        });

     


    });
<!DOCTYPE html>

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="enter a command.">

    <title>unilogue</title>

  <link rel="icon" href="favi.png">
  <link rel="stylesheet" href="https://unilogue.github.io/css/style.css">
  <script type="text/javascript" src="https://unilogue.github.io/js/jquery-1.11.3.min.js"></script>
 
  </head>

<body>

<header>
    
    <div id="prompt">enter the letter 'g' to load the div, notice how it keeps reloading if you enter the letter 'g' again? i don't want that to happen.</div>
    <br>
</header>

<div class="container"><p>&#62;&nbsp;</p><input class="inputs" type="text" placeholder="ENTER COMMAND" /></div>

</body>

</html>

2 个答案:

答案 0 :(得分:2)

如果你想检查一个元素是否已经存在,那么使用JQuery并检查元素的长度非常方便。如果长度为0,则不存在。类似的东西:

if($('#anElement').length)
    return;
else        
    $('<tag>Look! A Thing!</tag>').appendTo('#someOtherElementYouWantThisToAttachTo');

我会举出更具体的例子,但你发布了一堆代码。

编辑:

为什么不尝试这个?只需在if / else检查中添加几个子句即可。

$(document).ready(function() {

 $.ajaxSetup ({
     cache: false
 });



      // Check on keydown
     $('.inputs').keyup(function (e) {
            if (e.keyCode == 13) {

           var value = $(this).val();
           var ajax_load = "<p>LOADING<span class=\"blink\">_</span></p>";


          var loadGlossary = "https://unilogue.github.io/commands/glossary.asp";

           var errorLine = $("<p><span class=\"cmd\">&#62;&nbsp;UNKNOWN COMMAND</span></p><br>");
           var newLine = $('.inputs').clone(true).val('');

           var glossary = $("<div id=\"div3\"></div>");

          $.fn.gCmd = function() {
             $('.container').append(glossary);
             $("#div3").html(ajax_load).load(loadGlossary);
           };

           $.fn.newLine = function() {
            $('.container').append("<p>&#62;&nbsp;</p>").append(newLine);
            $(this).prop('disabled', true);
            $(this).removeClass('inputs');
            $('.inputs').replaceWith(newLine);
            $('.inputs:first').focus();
           };

          // Tiny jQuery Plugin
          // by Chris Goodchild
          $.fn.exists = function(callback) {
            var args = [].slice.call(arguments, 1);

            if (this.length) {
              callback.call(this, args);
            }

            return this;
          };

          // Usage
          $(glossary).exists(function() {
            // maybe the function to prevent .gCmd() could go here?
            this.append('<p><span class=\"cmd\">&#62;&nbsp;[g]lossary is already open!</span></p><br>');
          });

            if (value == 'g' && !($('#div3').length)) { // If input value is div3
                $(this).gCmd();
            } else if (value !== '' && $(glossary).length === 0) { // If input value is wrong
                $('.container').append(errorLine);
            }
/*appends to all lines */ $(this).newLine();
          }
        });




    });

答案 1 :(得分:-1)

我将id更改为class并添加了一个子句,该子句指定如果重新输入命令,jQuery必须删除该类并附加消息。

$(document).ready(function() {

 $.ajaxSetup ({
     cache: false
 });


      // Check on keydown
     $('.inputs').keyup(function (e) {
    		if (e.keyCode == 13) {

           var value = $(this).val();
           var ajax_load = "<p>LOADING<span class=\"blink\">_</span></p>";


           var loadGlossary = "https://unilogue.github.io/commands/glossary.asp";

           var errorLine = $("<p><span class=\"cmd\">&#62;&nbsp;UNKNOWN COMMAND</span></p><br>");
           var newLine = $('.inputs').clone(true).val('');

           var glossary = $("<div class=\"div3\"></div>");

           var gOpen = $('<p><span class=\"cmd\">&#62;&nbsp;[g]lossary is already open!</span></p><br>');

            $.fn.gCmd = function() {
             $('.container').append(glossary);
             $(".div3").html(ajax_load).load(loadGlossary);
           };

           $.fn.newLine = function() {
            $('.container').append("<p>&#62;&nbsp;</p>").append(newLine);
            $(this).prop('disabled', true);
            $(this).removeClass('inputs');
            $('.inputs').replaceWith(newLine);
            $('.inputs:first').focus();
           };

            if (value == 'g' && !($('.div3').length)) { // If input value is div3
                $(this).gCmd();
            } else if (value == 'g'  && ($('.div3').length)) { // If div3 is present
                $(glossary).removeClass('div3');
                $('.container').append(gOpen);
            } else if (value != '') { // If input value is wrong
                $('.container').append(errorLine);
            }

/*appends2all*/ $(this).newLine();
          }
        });

     $('html').keydown(function(e) {
      if (e.which == 88 && e.ctrlKey) { // value = help
        $('#cmd').show();
        $('#prompt').hide();
    }
         });


    });
<!DOCTYPE html>

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="enter a command.">

  <link rel="stylesheet" href="https://unilogue.github.io/css/style.css">
  <link href='https://fonts.googleapis.com/css?family=Source+Code+Pro:400,700,300' rel='stylesheet' type='text/css'>
  <script type="text/javascript" src="https://unilogue.github.io/js/jquery-1.11.3.min.js"></script>
  </head>

<body>

<header>
    <div id="prompt">enter the letter 'g'.</div>
</header>

<div class="container"><p>&#62;&nbsp;</p><input class="inputs" type="text" placeholder="ENTER COMMAND" /></div>

</body>

   
</html>