Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/extjs/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在jquery中触发全局变量_Javascript_Jquery_Global Variables - Fatal编程技术网

Javascript 在jquery中触发全局变量

Javascript 在jquery中触发全局变量,javascript,jquery,global-variables,Javascript,Jquery,Global Variables,我需要将另一个页面中的H1内容存储到一个变量中,以便以后在代码中访问。我想出了以下代码: var h1Text; $.get('p1.html', function(data) { h1Text = $('<div>', {html: data }).find("h1").text(); console.log("Test 1 = " + h1Text); }, "html"); //some code here //some code there //anot

我需要将另一个页面中的H1内容存储到一个变量中,以便以后在代码中访问。我想出了以下代码:

var h1Text;
$.get('p1.html', function(data) {
    h1Text = $('<div>', {html: data }).find("h1").text();
    console.log("Test 1 = " + h1Text);
}, "html");

//some code here

//some code there

//another code here

console.log("Test 2 = " + h1Text);

测试2应该在测试1之后运行,不是吗?这就是为什么测试2给出“未定义”值的原因吗?我需要在存储变量“h1Text”之后访问它。我做错了什么?

测试2在测试1之前运行,因为$.get需要等待响应,并在收到响应时调用success函数。如果您需要访问文本,您应该在获得数据后再访问。因此,根据您的代码,您应该从您提供的用于get的success函数中调用使用h1Text的函数。

我用$.get总结了一些我需要的代码,这是您提到的一部分,它起到了作用。非常感谢:)
<h1 id="Title">Camp. Bras. Stock Car - 2ª Bateria</h1>
Test 2 = undefined
Test 1 = Camp. Bras. Stock Car - 2ª Bateria