[英]How to stop iFrame from reloading
我正在嘗試通過在 onload 事件中添加參數來將參數傳遞給 iFrame,如下所示:
<iframe name="myframe" src="http://test.com/hello" onload=" frames['myframe'].location.href='http://test.com/hello?uname='+getUserName();">
</iframe>
(getUserName 是我的自定義函數)
但是 iFrame 會一遍又一遍地加載。 如何僅使用 javascript (而不是任何 js 框架)來阻止這種情況?
注意:由於某些原因,我只能編寫內聯 javascript 腳本。
您可以設置一個全局標志(選擇一個不與任何其他名稱沖突的適當名稱):
if (window.frames['myframe'] && !window.userSet){
window.userSet = true;
frames['myframe'].location.href='http://test.com/hello?uname='+getUserName();
}
或者,您可以為元素設置自定義屬性:
var userSet = this.getAttribute('data-userset');
if (window.frames['myframe'] && !userSet){
this.setAttribute('data-userset', 'true');
frames['myframe'].location.href='http://test.com/hello?uname='+getUserName();
}
或者,如果您以后不必再次調用事件處理程序,則可以將其刪除:
if (window.frames['myframe']){
this.onload = null;
this.setAttribute('onload', '');
frames['myframe'].location.href='http://test.com/hello?uname='+getUserName();
}
順便提一句。 你有什么if
語句? 我認為無論如何,這將永遠是true
。
因為 HREF 在加載時會發生變化,而 HREF 的更改將重新加載onload
。
因此,您必須將onload
刪除到其他事件。
使用計數器,以便僅在第一次重定向時。
最初它是0
並重定向,第二次是1
等等,因此不重定向。
<script>var counter = 0</script>
<iframe name="myframe" src="http://test.com/hello"
onload="if (window.frames['myframe'] && counter++ === 0){ frames['myframe'].location.href='http://test.com/hello?uname='+getUserName();}">
</iframe>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.