【问题标题】:Using typescript, how to update HTML element's value and text.?使用打字稿,如何更新 HTML 元素的值和文本。?
【发布时间】:2017-02-14 05:38:55
【问题描述】:

我想使用打字稿更新html 元素的某些属性。有可能这样做吗?这是我的代码

HTML:-

<a ref="#" id="userProfileName" style="padding-top: 0px; padding-bottom: 0px; padding-right: 10px; padding-left: 10px;">
<img src="" alt="" id="userProfilePic" class="profile-img" style="width: 56px; height: 50px;"></a>

打字稿:-

document.getElementById('userProfilePic').src = profile.picture;
document.getElementById('userProfileName').textContent = profile.given_name;

我得到的错误:-

error TS2339: Property 'src' does not exist on type 'HTMLElement'.

【问题讨论】:

    标签: html typescript


    【解决方案1】:

    document.getElementById 函数返回一个类型为 HTMLElement 的元素,它没有 src 属性。
    你需要输入 assert 它到HTMLImageElement:

    (document.getElementById('userProfilePic') as HTMLImageElement).src = profile.picture;
    

    HTMLAnchorElement 也是如此,但 textContent 可以直接从 HTMLElement 访问,因此无需强制转换。

    【讨论】:

    • 谢谢 Nitzan :) 效果很好。作为感谢,我想让你知道,在宝莱坞有一部名叫托默(Paan Singh Tomer)的电影,看它你会喜欢的:)
    • 谢谢,找到它imdb.com/title/tt1620933,它刚刚添加到我的列表中。
    【解决方案2】:

    这是您从 Typescript 文件中操作 HTMLElement 的方式。 (角度框架)

    HTML:

      <span id="alert_VotePg"></span>
    

    打字稿文件:

       var alertZ = document.getElementById('alert_VotePg');
       alertZ!.innerText ="1) Choose a movie 2) The name and email cannot be blank.";
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-27
      • 1970-01-01
      • 2020-07-25
      • 2020-07-02
      • 1970-01-01
      • 2021-11-23
      • 1970-01-01
      相关资源
      最近更新 更多