使用TypeScript设置window.location


81

以下TypeScript代码出现错误:

 ///<reference path='../../../Shared/typescript/jquery.d.ts' />
 ///<reference path='../../../Shared/typescript/jqueryStatic.d.ts' />

 function accessControls(action: Action) {
    $('#logoutLink')
        .click(function () {
            var $link = $(this);
            window.location = $link.attr('data-href');
        });

 }

我收到以下内容的带下划线的红色错误:

$link.attr('data-href'); 

消息说:

Cannot convert 'string' to 'Location': Type 'String' is missing property 'reload' from type 'Location'

有人知道这意味着什么吗?

Answers:


156

window.location是类型Location,而.attr('data-href')返回一个字符串,所以你必须给它分配到window.location.href这是字符串类型的了。为此,替换您的以下行:

window.location = $link.attr('data-href');

为此:

window.location.href = $link.attr('data-href');

1
我注意到,在当今的浏览器中,设置window.location = "some string"具有特殊的行为,请参见此处:stackoverflow.com/questions/2383401/…-请参阅有关同一站点,相同来源和XHR行为的注释。

23

您错过了href

标准,为了在使用window.location.hrefwindow.location在技术上包含一个对象:

Properties
hash 
host 
hostname
href    <--- you need this
pathname (relative to the host)
port 
protocol 
search 

尝试

 window.location.href = $link.attr('data-href');
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.