【问题标题】:Get and print hash in iframe在 iframe 中获取并打印哈希
【发布时间】:2017-10-11 16:43:08
【问题描述】:

我想从这个网址获取哈希

http://www.mywebsite.com/#/aaaaaaaa

啊啊啊啊

并添加到 iframe:

<iframe src="http://www.example.com/url/aaaaaaaa" frameborder="0">

Javascript 代码:

<script>
var hhash = window.location.hash.substr(1);
alert(hhash);
</script>

【问题讨论】:

  • 然后呢?您已经拥有的代码有什么问题? IE。你的问题是什么?另外,您想将哈希添加到 iframe,还是添加到 iframe 的 src?
  • 是的,@Teemu 我想用 javascript 在 iframe 中自动打印“aaaaaaaa”
  • stackoverflow.com/questions/24603580/… 虽然您似乎误用了location.hash,也许您应该改用查询字符串?
  • 感谢您抽出宝贵时间@Teemu,但我无法编辑此代码,我是 javascript 初学者

标签: javascript jquery


【解决方案1】:

您还可以使用 lastIndexOf() 函数定位 URL 中最后一次出现 / 字符,然后使用 substr() 函数返回从该位置开始的子字符串:

 var hhash =(window.location.href.substr(window.location.href.lastIndexOf('/') + 1));
 document.write("<iframe src=\"example.com/url/\""+hhash+"frameborder=\"0\">");

【讨论】:

  • 谢谢@Osama,但我想像这样在 iframe 中打印 var hhash .. "aaaaaaaa"
  • 非常感谢奥萨马先生
  • 这不会写入有效的 HTML。
  • 它只会检查 document.write() 行的语法 我使用的是 iPhone 而不是笔记本电脑,所以那里可能有错误
【解决方案2】:

您的标题和问题有点误导。 如果您只想打印哈希标签,您可以创建一个元素并将innerText 设置为您的哈希,如下所示:

// Use hash instead of href here! :) This is just to make the example work
const lastPart = window.location.href.split( '/' ).pop();
document.querySelector( '.hash' ).innerText = lastPart;
&lt;div class="hash"&gt;&lt;/div&gt;

如果你想改变 iFrame 的 src,你可以使用第一个例子结合 setAttribute。

// Use hash instead of href here! :) This is just to make the example work
const lastPart = window.location.href.split( '/' ).pop();
const src = 'http://example.org/url/' + lastPart;
document.querySelector( '.hash' ).setAttribute( 'src', src );
document.querySelector( '.url' ).innerText = 'iframe points to ' + src;
<iframe class="hash"></iframe>
<div class="url"></div>

【讨论】:

  • 感谢您的宝贵时间,但我只想打印最后一个文件夹mywebsite.com/#/aaaaaaaa .... "aaaaaaaa" 在 iframe 中像这样
  • 我的第二个例子应该做到这一点
  • 什么不起作用(任何错误?)以及您的预期结果是什么?
  • 空白页,我无法在 iframe 中获得“aaaaaaaa”
  • 好的,你真正的 iframe 也会加载 example.com?我认为您正在加载的页面已经检查了该位置。如果您只想在页面上显示哈希,则不需要 iframe。只需通过添加&lt;div class="hash"&gt;&lt;/div&gt; 来使用第一个解决方案 :) 否则您需要解释一下您到底想要什么
【解决方案3】:

您可以通过以下方式获取哈希部分(不带#/):

var hash = window.location.hash.replace('#/', '');

然后你得到当前的 iframe src 属性:

var src = document.getElementsById('YourIframeId').getAttribute('src');

现在你更新 iframe src:

document.getElementsById('YourIframeId').setAttribute('src',src + '/' + hash);

【讨论】:

    猜你喜欢
    • 2022-12-10
    • 2016-11-01
    • 1970-01-01
    • 2012-08-10
    • 2014-11-30
    • 2017-09-30
    • 2016-12-18
    • 2011-02-09
    • 2012-10-23
    相关资源
    最近更新 更多