2013-12-15 23 views
0

當「this._try == 1」時重定向不起作用?重定向如果 - Javascript

下面是完整的JS,但它不再是在點擊時檢查try == 1,而是在窗口關閉時自動檢查。

function ouvre(fichier) { 

    ff=window.open(fichier,"popup","width=600px,height=300px,left=50%,top=50%") 
    //this._try = 1;  
    setTimeout('this._try = 1;', 4000); 
} 


function playMovie(_try) { 
    if (this._try == 1) { playsavideo(); } 
    else { alert('You must share to unlock.'); } 
} 

function playsavideo(type) { 
    { 
    window.location = "http://google.com" 


    } 
} 

窗口由這家名爲...

<a href="#" onClick="ouvre('https://twitter.com/share?url=https%3A%2F%2Fdev.twitter.com%2Fpages%2Ftweet-button');return false">Test</a> 
+0

嘗試將它移動到setTimeout的回調? – brandonscript

+0

這看起來不像你想給我們看的代碼。有些作品被註釋掉了,爲什麼你使用'this'是你創建一個對象?顯示所有的代碼? –

+0

@popnoodles他的代碼仍然沒有意義,你能明白這個'this'是什麼嗎? –

回答

2

您嘗試使用this作爲值/全局變量的載體。
但是this是一個「相對」變量,它總是與它所處的對象的實例有關。
在你的代碼中沒有實例。即使是這樣,函數內部的this也會引用 這個函數,而其他的this以外的函數很可能會引用另一個東西。

雖然全球變量不是很好的做法。試試這個:

var i_am_a_global_var = false; 
function ouvre(fichier) { 
    ff=window.open(fichier,"popup","width=600px,height=300px,left=50%,top=50%"); 
    setTimeout(function(){window.i_am_a_global_var=true;bobo();}, 4000); 
} 

function bobo(){ 
    if (window.i_am_a_global_var) { 
    window.location.href = "http://www.google.com/" 
    } 
} 
  1. 定義一個全局變量
  2. 當超時發生就西港島線回調封閉(function(){...}),這將調用bobo功能。
  3. 如果全局變量爲true,bobo函數就是發生重定向的地方。

你可以這樣做,由於其mught更改this._try但如果你想要做x秒後重定向所有,那麼短版將其他邏輯:

window.open(fichier,"popup","width=600px,height=300px,left=50%,top=50%"); 
setTimeout('window.location.href = "http://www.google.com/"', 4000); 
+0

有人指出它應該是'window.location.href = ...'或者兩者都有效嗎? – Popnoodles

+0

完美的作品!謝謝你,itay :) –

+0

@popnoodles既可以工作,但爲了安全起見,我將編輯爲您的版本 –

1

可以與內容window.location.href = "http://www.google.com/"添加新的功能,然後編輯的setTimeout( '[函數名稱]',4000)。

0

你要通過函數setTimeout。我想你應該在函數中做重定向。

var that = this; 
function ouvre(fichier) { 
    ff=window.open(fichier,"popup","width=600px,height=300px,left=50%,top=50%"); 
    //this._try = 1; 
    var fn = function() { 
     that._try = 1; 
     window.location = 'http://google.com'; 
    } 
    setTimeout(fn, 4000); 
} 
+0

這也適用,它不使用全局變量,所以我要實現這一點。非常感謝! –