从HTML输入onchange属性

时间:2020-02-18 13:34:34

标签: javascript html typescript

如果我有这样的JavaScript index.js 文件:

function foo(val) {
  console.log(val);
}

和如下的 index.html HTML文件:

...
<script src="./index.js"></script>
<div id="container">
  <label>bar
    <input type="radio" name="radio" value="bar" onchange="foo(value);"/>
  </label>
  <label>baz
    <input type="radio" name="radio" value="baz" onchange="foo(value);"/>
  </label>
...

这会在我选中单选按钮时记录barbaz

我要调用在{strong> index.ts TypeScript文件中定义的foo(value),如下所示:

let foo = (value: string): void => {
  console.log(value);
};

index.html 中,将<script src="./index.js"></script>更改为<script src="./src/index.ts"></script>,然后使用宗地构建应用程序,但是生成的生成文件无法调用该函数,记录referenceError: setLayer is not defined

我知道理论上浏览器对TypeScript并不了解,只知道JavaScript,但是在dist dir中使用宗地进行编译后,我看到了一堆*js文件,我认为其中可能包括已编译的foo()函数。

所以问题是:如何像HTML文件一样从HTML输入onchange属性调用TS文件中的函数?

最后但并非最不重要:要构建我的应用程序,我调用parcel start(甚至是parcel run build),而我的package.json看起来像这样:

{
  "name": "app_test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start:build": "tsc -w",
    "start": "parcel index.html",
    "build": "parcel build --public-url . index.html"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
  },
  "devDependencies": {
    "parcel-bundler": "^1.12.4",
    "typescript": "^3.7.5"
  }
}

2 个答案:

答案 0 :(得分:3)

问题:

将js捆绑在一起的工具如Parcel和Webpack,将所有模块包装在IIFE中,因此,在Parcel处理后,您的index.ts函数foo不是全局的,您不能简单地从html访问它归档。未经处理(例如:<script src="./index.js"></script>foo是全局的。

解决方案:

foo设置为全局。

// index.ts
function foo(val: string) {
  console.log(val);
}

window.foo = foo;

Codesandbox

答案 1 :(得分:0)

尝试直接指向index.ts中的已编译文件,而不是直接从index.html文件中引用/dist

<script src="dist/index.js"></script>

正如您正确地指出的那样,TypeScript只是JavaScript的一个超集,不能被您的浏览器解释-仅在将其编译为JavaScript之后。

相关问题