2016-10-13 42 views
3

當您單擊按鈕時,我試圖將位置從'currentUrl'更改爲'currentUrl/somePage.html'。使用JavaScript重定向到(currenturl)/example.html onclick

代碼不依賴於硬編碼url是很重要的。相反,它應該抓取用戶所在的當前網址,並將「/somePage.html」的值附加到該網址的末尾。

我已經做了一些查找,發現window.location.href將返回我當前的URL位置,並且該window.location將重定向到一個新的。但是,當我嘗試將它們放在一起時,單擊我的按鈕時出現「未定義函數」錯誤。

我的代碼看起來是這樣的......

HTML:

<button class="btn btn-default" onclick="redirectToPage()">Some Page</button> 

JS:

$(function() { 

    function redirectToPage() { 
     var url = window.location.href; 
     window.location(url + "/somePage.html"); 
    } 
}); 

你們都是可愛的人!謝謝您的幫助!

回答

3

如果你打算使用jQuery,那麼你應該使用它的所有功能:

(這一點,我決不會建議內嵌JavaScript)

HTML:

<button class="btn btn-default js-do-redirect">Some Page</button> 

jQuery的:

$(document).ready(function(){ 
    $('.js-do-redirect').on('click', function(){ 
    var url = window.location.href; 
    window.location = url + "/somePage.html"; 
    }); 
}); 

或者如果您想使其可重複使用:

HTML:

<button class="btn btn-default js-do-redirect" data-redirect-to="/somePage.html"> 
    Some Page 
</button> 

的jQuery:

$(document).ready(function(){ 
    $('.js-do-redirect').on('click', function(){ 
    var url = window.location.href; 
    var page = $(this).data('redirect-to'); 
    window.location = url + page; 
    }); 
}); 

推薦閱讀Decoupling Your HTML, CSS, and JavaScript

+0

太棒了!謝謝! – venuxv

0

redirectToPage只在處理程序函數的作用域內定義。你需要把它移到外面。

1

你很近。 window.location不是一個函數,而是一個propery。

function redirectToPage() { 
    var url = window.location.href; 
    window.location = url + "/somePage.html"; 
}