Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/13.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从我的域上的另一个页面将文本返回到输入文本框中_Javascript_Jquery - Fatal编程技术网

使用JavaScript从我的域上的另一个页面将文本返回到输入文本框中

使用JavaScript从我的域上的另一个页面将文本返回到输入文本框中,javascript,jquery,Javascript,Jquery,我正在尝试将域上另一页的文本返回到输入文本框中。我可以返回div DivThisPage中的文本,但似乎无法从加载到文本输入字段txtValue的div中获取文本 function getValue() { $("#DivThisPage").load("http://another-page-on-my-site #DivTheOtherPage"); //This is working and I see "test" on this page. var myVal = $('#D

我正在尝试将域上另一页的文本返回到输入文本框中。我可以返回div DivThisPage中的文本,但似乎无法从加载到文本输入字段txtValue的div中获取文本

function getValue() {
  $("#DivThisPage").load("http://another-page-on-my-site #DivTheOtherPage"); //This is working and I see "test" on this page. 
  var myVal = $('#DivThisPage').val(); //I've tried both DivThisPage and DivTheOtherPage but get nothing
  $("#txtValue").val(myVal);
}
以下是此页面上的HTML:

<button onclick="getValue()">Get Value</button>
<div id="DivThisPage"></div>
<input type="text" id="txtValue" name="txtValue" />
“我的网站”上其他页面的html:

<div id="DivTheOtherPage">test</div>
但是,当我在执行后检查页面上的元素时,我看到:

<div id="DivThisPage">
<div id="DivTheOtherPage">test</div>
</div>

但是当我调试脚本时,myVal总是空的。

这里有两个问题。首先,div元素没有value属性,因此val方法不适用于它们。假设您想从问题的上下文中获取元素中的文本,请使用html或文本

其次,loadundthehood使用的AJAX调用是异步的。这意味着您需要使用callback参数,以便在数据更新后从DOM读取数据

获得价值 jQueryfunction${ $'按钮'。单击'按钮',函数{ $DivThisPage.load/relative-path DivTheOtherPage,函数{ var myVal=$'DivTheOtherPage'.text; $txtValue.valmyVal; }; }; }; 还要注意,这里使用了一个不引人注目的事件处理程序。内联事件属性现在被认为是不好的做法,因为它们将HTML和JS逻辑捆绑得太紧,应该尽可能避免使用

此外,如果您正在呼叫自己网站上的某个位置,请使用相对链接。

使用此链接:

函数getValue{ $DivThisPage。loadhttp://another-page-on-my-site DivTheOtherPage,functionresponse,status,xhr{ var myVal=$'DivThisPage'.val; $txtValue.valmyVal; }; }div元素没有值。您的意思是要将加载的div中的文本输入到txtValue输入中吗?还请注意,您需要使用load的callback参数,因为AJAX调用获取的数据是异步的。对于div,使用文本或html,而不是值