javascript 使用TypeScript设置窗口位置

uqxowvwt  于 2023-02-15  发布在  Java
关注(0)|答案(5)|浏览(160)

我收到以下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'

有人知道这是什么意思吗?

bvpmtnay

bvpmtnay1#

window.location的类型是Location,而.attr('data-href')返回一个字符串,所以你必须把它赋给同样是字符串类型的window.location.href

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

对于这个:

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

pu3pd22g2#

您已错过href
标准,将window.location.href用作window.location在技术上是一个包含以下内容的对象:

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

尝试

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

smtd7mpg3#

Location接口上有一个assign方法,当传递字符串时,它可以很好地处理typescript,并且与window.location = LOCATION的工作原理相同。

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

这个方法似乎已经存在很长时间了(IE 5.5!)。
https://developer.mozilla.org/en-US/docs/Web/API/Location/assign

oiopk7p5

oiopk7p54#

在实现复杂的PayPal集成时,我注意到使用window.location的一个非常令人信服的理由,即it does not require  SAME ORIGIN
因此,我们做了如下操作:

(<any> window).location = myUrl;

取代:

window.location.href = myUrl;

在OP的情况下:

var myUrl = $link.attr('data-href');
kqlmhetl

kqlmhetl5#

只需添加href
就像这样:

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

相关问题