【问题标题】:Set window.location with TypeScript使用 TypeScript 设置 window.location
【发布时间】:2012-10-17 21:37:33
【问题描述】:

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

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

【问题讨论】:

    标签: javascript jquery typescript


    【解决方案1】:

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

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

    对于这个:

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

    【讨论】:

    • 我注意到,在当今的浏览器中,设置 window.location = "some string" 具有特殊行为,请参见此处:stackoverflow.com/questions/2383401/… - 请参阅有关同站点、同源和 XHR 行为的 cmets。
    【解决方案2】:

    你错过了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');
    

    【讨论】:

      【解决方案3】:

      只需添加href

      像这样:

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

      【讨论】:

      • 这与the accepted answer 中的解决方案相同。 在回答已有答案的旧问题时,请确保提供新颖的解决方案或比现有答案更好的解释。
      猜你喜欢
      • 2011-04-08
      • 2016-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-20
      • 1970-01-01
      相关资源
      最近更新 更多