Javascript 来自另一个页面的 getElementById

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27930780/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:56:12  来源:igfitidea点击:

getElementById from another page

javascripthtmlgetelementbyidfitnesse

提问by Safi Naseen

I am trying to get one divfrom one webpage URL to another webpage and display in plain text using getElementByIdwithout using AJAX or jQuery because I'm going to implement it in FitNesse. Is there a way to pass the URL?

我试图div从一个网页 URL 获取另一个网页,并在getElementById不使用 AJAX 或 jQuery 的情况下以纯文本显示,因为我将在 FitNesse 中实现它。有没有办法传递网址?

回答by Mic

You could load the URL in a hidden iframe.

您可以在隐藏的 iframe 中加载 URL。

Then use iframe.contentWindow.document.getElementById($id) as outlined here: How to pick element inside iframe using document.getElementById

然后使用 iframe.contentWindow.document.getElementById($id) 如下所述:How to pick element inside iframe using document.getElementById

Something along the lines of:

类似的东西:

<iframe src="urlWithinYourDomain.html" style="display:none"></iframe>

Followed by a function something like:

后跟一个类似的功能:

var divElement = document.getElementById('iframeId').contentWindow.document.getElementById('elementIdOnSourcePage');
document.getElementById('targetParentId').appendChild(divElement);

I'm afraid I can't test this at the moment, so there may be syntax errors, but I think it conveys the idea. It's a bit of a dirty approach, but given your constraints it's the best way I can see to do what you're asking.

恐怕我目前无法对此进行测试,因此可能存在语法错误,但我认为它传达了这个想法。这有点肮脏的方法,但考虑到您的限制,这是我能看到的最好的方式来完成您的要求。

回答by Adam Joseph Looze

On page 1.

在第 1 页。

<div id="dataDiv">1234</div>
<a id="getData" href="">Page2</a>

<script>
var data = document.getElementById('dataDiv').innerHTML;
//This will get the content from the div above with the id of "dataDiv"

document.getElementById("getData").setAttribute("href","page2.html?var="+data);
//This will set the url of the anchor with the id of "getData" with your url and the passing data.
</script>

And on page 2

在第 2 页

  function getUrlVars() {
  var vars = {};
  var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
      vars[key] = value;
  });
  return vars;
  }
  var var1 = getUrlVars()["var"];

This will send the content in your div on page one to page two. the result url on page 1 will be page2.html?var=1234

这会将您 div 中的内容从第一页发送到第二页。第 1 页上的结果 url 将是 page2.html?var=1234