在var中存储另一个页面H1内容,并检查是否有's单词

Store another page H1 content in var and check if there's a word

本文关键字:是否 检查 单词 存储 var 另一个 内容 H1      更新时间:2023-09-26

我有我的索引页和另一个名为'p1.html'的页面。我需要将p1.html中的H1内容存储到索引页上的一个变量中,以便稍后检查var中的H1是否包含特定的单词

类似:

var h1Content = $.get('p1.html', function(html){
    $.text($('h1',html).text());
  });
// some other code blablabla
// some other code blablabla
// some other code blablabla
if (h1Content.indexOf("Stock") != -1) {
    console.log("H1 has Stock");
} else if (h1Content.indexOf("Turismo") != -1) {
            console.log("H1 has Turismo");
}

这里的p1.html H1:

   <h1 id="Title">Camp. Bras. Stock Car - 2ª Bateria</h1>

我做错了什么?

我的想法是,我可以使用上面的概念,在这段代码中:
var TimerLoad, TimerChange;
    var MaxNum, Rafraichir, Changement, ClassementReduit, ClassementReduitXpremier;
    var UrlRefresh, UrlChange;
    Rafraichir = 3000;
    Changement = 15000;
    MaxNum = 1;
    ClassementReduit = 0;
    ClassementReduitXpremier = 10;
    // VAR WITH H1 from p1 stored goes here <<<<<
    function Load(url, target) {
        var xhr;
        var fct;
        if (UrlChange) url = UrlRefresh;
        else UrlRefresh = url;
        UrlChange = 0;
        if (TimerLoad) clearTimeout(TimerLoad);
        try {
            xhr = new ActiveXObject("Msxml2.XMLHTTP")
        } catch (e) {
            try {
                xhr = new ActiveXObject("Microsoft.XMLHTTP")
            } catch (e2) {
                try {
                    xhr = new XMLHttpRequest
                } catch (e3) {
                    xhr = false
                }
            }
        }
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4 && xhr.status == 200)
                if (ClassementReduit == 0) document.getElementById(target).innerHTML = xhr.responseText;
                else document.getElementById(target).innerHTML = ExtraireClassementReduit(xhr.responseText)
                //console.log("18");
                // IF/ELSE CONDITIONS TO CHECK IF H1 have a specific word GOES HERE <<<
        };

你应该这样做:

var h1Content;
$.get('p1.html', function(html){
   h1Content = $('h1',html).text();
});
function checkH1() {
  if (h1Content) {    
   if (h1Content.indexOf("Stock") != -1) {
     console.log("H1 has Stock");
   } else if (h1Content.indexOf("Turismo") != -1) {
     console.log("H1 has Turismo");
   }
  } else {
    setTimeout(checkH1, 1000); //In case h1Content is empty because the ajax call didn't retrieve anything yet, it waits 1 second and fires this function again.
  }
}
checkH1(); //You can call this from wherever you want, may be attaching it as an event.

不要忘记$.get()是一个异步调用,所以进程不会阻塞,直到它得到响应,它将继续工作并运行$.get()调用下面的行,变量h1Content将是undefined