javascript - 如何阻止 jQuery 加载已存在的 div

标签 javascript jquery ajax

我为我的网站创建了一个模拟控制台,但我面临一个问题,每当输入值提交多次时,jQuery 就会重新加载 div,因为它标记有特定的 id。

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

如果 div 已存在,如何阻止 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 忽略整个 else 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>

最佳答案

如果您想检查某个元素是否已存在,那么使用 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();
          }
        });




    });

关于javascript - 如何阻止 jQuery 加载已存在的 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34668986/

相关文章:

javascript - 尝试 AJAXify 这个 Rails 4 方法调用并收到 500 错误

javascript - IE11 在所有其他浏览器工作的地方抛出 "SCRIPT1014: invalid character"

javascript - 如何计算 RadGrid 中的记录数? (客户端、AJAX)

javascript按空格分割字符串,但忽略引号中的空格(注意不要也用冒号分割)

jquery - 如何一次完全删除每个 css 属性?

jquery - 增量正则表达式过滤器

jquery - 使用 jQuery 获取 URL 的 #anchor ?

c# - C# 和 VB lambda 是否有类似于 javascript 的**作用域链**问题?

javascript - mongodb中另一个模型中的数组中仅保存objectID

javascript - 使用elastic.js中止elasticsearch请求