我有我的索引页面和另一个名为' p1.html'的页面。我需要将p1.html中的H1内容存储到我的索引页面上的var中,然后稍后检查,如果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 <<<
};
答案 0 :(得分:0)
你应该这样做:
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
。