简体   繁体   English

JavaScript无法正常运行而没有警报

[英]Javascript not working without alert

Okay, this one is weird and I'm not entirely sure how to word the Title for this particular question. 好的,这很奇怪,我不太确定如何为该特定问题写标题。 I have a javascript function that is supposed to happen when the document is ready. 我有一个javascript函数,应该在文档准备就绪时发生。 The first part of the function calls a function that includes some added html pages into the page. 函数的第一部分调用一个函数,该函数包括一些添加到页面中的html页面。

The next part matches the last section of the current url page and finds them in the menu to to give it a selected class, along with the parent of the menu item. 下一部分与当前url页的最后一部分匹配,并在菜单中找到它们以为其提供选定的类,以及菜单项的父级。

The code works, but only with the 该代码有效,但仅适用于

    alert(lastpath); 

When the alert statement is removed, the lines below no longer function. 删除警报语句后,下面的行不再起作用。

    $( document ).ready(function() {

        w3IncludeHTML();
        lastpath=(window.location.pathname).split("/").slice(-1).pop();
        alert(lastpath);
        $('a[href$="'+lastpath+'"]').attr("class","selected");
        $('a[href$="'+lastpath+'"]').parent(".dropdown-content").prev().attr("class","selected");

    });

Does anyone know what could be happening here? 有人知道这里会发生什么吗?

You use the function from the JS library from w3schools . 您可以使用w3schools的JS库中的函数。 Just take a look at their code: 看看他们的代码:

function w3IncludeHTML() {
  var z, i, a, file, xhttp;
  z = document.getElementsByTagName("*");
  for (i = 0; i < z.length; i++) {
    if (z[i].getAttribute("w3-include-html")) {
      a = z[i].cloneNode(false);
      file = z[i].getAttribute("w3-include-html");
      var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        if (xhttp.readyState == 4 && xhttp.status == 200) {
          a.removeAttribute("w3-include-html");
          a.innerHTML = xhttp.responseText;
          z[i].parentNode.replaceChild(a, z[i]);
          w3IncludeHTML();
        }
      }      
      xhttp.open("GET", file, true);
      xhttp.send();
      return;
    }
  }
}

It is using a XMLHttpRequest object, so we are sure it's an asynchronous code. 它使用XMLHttpRequest对象,因此我们确定它是异步代码。 Most likely, after your call to this function, you use lines of code which depend on the success of ajax request. 最有可能的是,在调用此函数之后,您将使用取决于ajax请求成功与否的代码行。 This is, of course, not good (treating asynchronous code as a synchronous code), but the delay provided by alert function makes it work (sometimes ;) !). 当然,这不好(将异步代码作为同步代码进行处理),但是alert功能提供的延迟使其可以工作(有时;)!)。

Solution: make sure, what does the w3IncludeHTML function do and how to get rid of the synchronous code after its call. 解决方案:确保w3IncludeHTML函数做什么,以及如何在调用之后摆脱同步代码。 Or: try to find a way to detect when the ajax part of this function is completed. 或者:尝试找到一种方法来检测此功能的ajax部分何时完成。 Actually, it's right there: 实际上,它就在那里:

        if (xhttp.readyState == 4 && xhttp.status == 200) {
          a.removeAttribute("w3-include-html");
          a.innerHTML = xhttp.responseText;
          z[i].parentNode.replaceChild(a, z[i]);
          w3IncludeHTML();
        }

The function w3IncludeHTML defined in the w3Data library loads the content asynchronously. w3Data库中定义的功能w3IncludeHTML异步加载内容。 It offers no way to get notified when it has finished its job: 它无法在完成工作时获得通知:

 function w3IncludeHTML() { var z, i, a, file, xhttp; z = document.getElementsByTagName("*"); for (i = 0; i < z.length; i++) { if (z[i].getAttribute("w3-include-html")) { a = z[i].cloneNode(false); file = z[i].getAttribute("w3-include-html"); var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (xhttp.readyState == 4 && xhttp.status == 200) { a.removeAttribute("w3-include-html"); a.innerHTML = xhttp.responseText; z[i].parentNode.replaceChild(a, z[i]); w3IncludeHTML(); } } xhttp.open("GET", file, true); xhttp.send(); return; } } } 

A quick solution would be to alter the above function, and add the following code to your script: 一种快速的解决方案是更改以上功能,并将以下代码添加到脚本中:

function w3IncludeHTML(callback) {
  var z, i, file, xhttp;
  z = document.querySelector("[w3-include-html]");
  if (!z) {
    // notify caller that all is loaded
    if (callback) callback();
    return;
  }
  file = z.getAttribute("w3-include-html");
  z.removeAttribute("w3-include-html");
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4) {
      if (xhttp.status == 200) {
        z.innerHTML = xhttp.responseText;
      }
      w3IncludeHTML(callback);
    }
  }      
  xhttp.open("GET", file, true);
  xhttp.send();
}

This version will override the function provided by the w3Data library, and improve it. 此版本将覆盖w3Data库提供的功能,并对其进行改进。 You can now pass a callback function to w3IncludeHTML , in which you can be sure that all content is loaded (unless errors occurred of course): 现在,您可以将回调函数传递给w3IncludeHTML ,其中可以确保所有内容都已加载(当然,除非发生错误):

$( document ).ready(function() {
    w3IncludeHTML(function () {
      // Everything that depends on loaded content, should be done here:
      lastpath=(window.location.pathname).split("/").slice(-1).pop();
      // not needed: alert(lastpath);
      $('a[href$="'+lastpath+'"]').attr("class","selected");
      $('a[href$="'+lastpath+'"]').parent(".dropdown-content").prev().attr("class","selected");
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM