使用TypeScript设置window.location

61 javascript jquery typescript

我使用以下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');
        });

 }
Run Code Online (Sandbox Code Playgroud)

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

$link.attr('data-href'); 
Run Code Online (Sandbox Code Playgroud)

消息说:

Cannot convert 'string' to 'Location': Type 'String' is missing property 'reload' from type 'Location'
Run Code Online (Sandbox Code Playgroud)

有谁知道这意味着什么?

Nel*_*son 128

window.location是类型Locationwhile .attr('data-href')返回一个字符串,所以你必须将它分配给window.location.href字符串类型.为此替换以下行:

window.location = $link.attr('data-href');
Run Code Online (Sandbox Code Playgroud)

对于这一个:

window.location.href = $link.attr('data-href');
Run Code Online (Sandbox Code Playgroud)

  • 我注意到在今天的浏览器中,设置 `window.location = "some string"` 具有特殊行为,请参见此处:/sf/ask/166838101/ - 请参见关于同站点、同源和 XHR 行为的评论。 (4认同)

Nul*_*teя 18

你错过了href:

标准,在技术上window.location.href用作window.location包含以下内容的对象:

Properties
hash 
host 
hostname
href    <--- you need this
pathname (relative to the host)
port 
protocol 
search 
Run Code Online (Sandbox Code Playgroud)

尝试

 window.location.href = $link.attr('data-href');
Run Code Online (Sandbox Code Playgroud)


rob*_*uck 7

Location 接口上有一个assign方法,当传递字符串时,它可以与 typescript 完美配合,并且与window.location = LOCATION.

window.location.assign('http://example.com');
Run Code Online (Sandbox Code Playgroud)
interface Location {
    ...
    /** Navigates to the given URL. */
    assign(url: string | URL): void;
}
Run Code Online (Sandbox Code Playgroud)

该方法似乎已经存在很长时间了(IE 5.5!)。

https://developer.mozilla.org/en-US/docs/Web/API/Location/assign