document.getElementById在TypeScript中不起作用

时间:2017-08-15 15:25:54

标签: javascript typescript nativescript

我是TypeScript的新手并尝试创建一个简单的应用程序。同时我试图通过使用document.getElementById方法将元素值从HTML转换为TypeScript,并抛出此错误:

  

未定义参考错误文档。

我在下面使用以下代码:

<TextField hint="UserName" name="usernameID" id="usernameID" style="margin-top:5%"/> 

并尝试使用TypeScript方法获取它:

export function onLogin() {

    var username = document.getElementById('usernameID');
    console.log('username :: '+username);
    frame.topmost().navigate("views/choicepage/choicepage"); 
}

我不知道我在这里失踪了什么。

3 个答案:

答案 0 :(得分:1)

Nativescript不知道文档对象它的浏览器东西在android或ios应用程序中使用Nativescript不存在

答案 1 :(得分:0)

文档在nativescript中不存在。您需要使用@ViewChild()代替角色,或this.page.getViewById代表香草

答案 2 :(得分:-1)

我能够通过添加&#39; 已加载&#39;来解决该问题。属性为&#34; 页面&#34;然后创建一个具有相同名称的已加载属性的方法,该属性将具有页面的上下文。以下是代码。

<Page xmlns="http://schemas.nativescript.org/tns.xsd" loaded="pageLoaded">
<!--
Stack layout for ordering the HTML element at the login page
-->
<StackLayout class="p-20" orientation="vertical">

    <!--Fields for getting the username and password for input-->
    <TextField hint="UserName" id="usernameID" style="margin-top:5%"/> 

    <TextField hint="Password"  id="passwordID" autocorrect="false" secure="true" style="margin-top:3%"/>

    <!--Login button here-->
    <Button text="login" tap="onLogin" id="logInButton" class="btn btn-primary btn-active" style="margin-top:5%"/>
    </StackLayout>

这里是TypeScript

import { EventData } from 'data/observable';
import { Page } from 'ui/page';
import { TextField } from 'ui/text-field';
import { Button } from 'ui/button';

let pageLoaded = (args : EventData) =>{
    let page = <Page> args.object;
    let textValue = <TextField>page.getViewById('usernameID');
    let logInButton= <Button>page.getViewById('signUpButton');

    logInButton.on('tap',(args:EventData)=>{
        console.log('textValue :: '+textValue.text);
    });
}
export {pageLoaded}

感谢您的帮助......干杯:)。

相关问题