【问题标题】:How to define functions within a function in typescript?如何在打字稿的函数中定义函数?
【发布时间】:2018-12-27 08:11:34
【问题描述】:

我知道基本的 Javascript,但在 Typescript 文件中遇到问题。我正在使用 Ionic 框架来测试一个页面,理论上用户可以像在 Tinder 上一样“滑动”,只是为了好玩。

我已经编写了所有的 JS,因为我是从 Codepen 移过来的,但我似乎无法通过 Typescript 的语法。

Javascript:

var tinderContainer = document.querySelector('.tinder');
var allCards = document.querySelectorAll('.tinder--card');
var nope = document.getElementById('nope');
var love = document.getElementById('love');

function initCards(card, index) {
  var newCards = document.querySelectorAll('.tinder--card:not(.removed)');

  newCards.forEach(function (card, index) {
    card.style.zIndex = allCards.length - index;
  }
}

Typescript(我使用 Google 和 SOF 的答案汇总而成):

export class TestPage {

  constructor(public navCtrl: NavController) {
  }

  tinderContainer = document.querySelector('ion-content');
  allCards = document.querySelector('.tinder--card');
  nope = document.getElementById('nope');
  love = document.getElementById('love');

  declare initCards(card,index) {
    newCards = document.querySelectorAll('.tinder--card:not(.removed)');

    newCards.forEach((card,index)) {
      card.style.zIndex = allCards.length - index;
    }
  } 
}

【问题讨论】:

    标签: ios ionic-framework mobile ionic3 hybrid-mobile-app


    【解决方案1】:

    一些提示是: 在你的函数中使用let newCards,因为你必须声明你的变量。

    你的 forEach 应该是这样的。

    newCards.forEach((card, index) => {
        ...    
    });
    

    但为了使用像 card.style.zIndexallCards.length 这样的语法,您将拥有声明变量类型..

    对于未知模型,您可以使用类似card['style']['zIndex']

    您还必须使用this 来访问类属性,例如this.allCards

    【讨论】:

    • 我可以澄清一下吗?根据 Typescript 文档,如果我在“导出类”下声明变量,那么我不应该使用“let”,而应该只使用“newCards = ....”。这是真的吗?
    • 我刚刚按照您的建议进行了更改,但是引用您的用户名,“itdoesn'twork”。
    • 回答你的let问题,你的newCards=...initCards()下面,所以你需要使用let
    猜你喜欢
    • 2016-09-04
    • 2020-09-18
    • 2019-08-03
    • 2018-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-25
    相关资源
    最近更新 更多