[英]Problem with JS function in TS file with HTML
I am building simple sharepoint webpart and i have a problem with using a function in my main file from other module file.我正在构建简单的 sharepoint webpart,我在其他模块文件的主文件中使用 function 时遇到问题。
Part of the file JSFunctions.module.js (file where i create my function):文件 JSFunctions.module.js 的一部分(我创建函数的文件):
function getApi(){
[my code]...
};
export { getApi }
Part of the file TestWebpartWebPart.ts (main file with body of my webpart):文件 TestWebpartWebPart.ts 的一部分(带有我的 webpart 正文的主文件):
import { getApi } from './JSFunctions.module.js';
this.domElement.innerHTML = `
<input type="text" id="userEmailInput"><br><br>
<input type="Button" Value="Przycisk" onClick=${getApi()}><br><br>
<div id="html_BirthdayTable"></div>
`;
Everythng is fine with html code, but i have problem wih onClick=${getApi()}. html 代码一切正常,但我对 onClick=${getApi()} 有问题。
When i type onClick${getApi()} there is error on the page: "Object(...) os not a function"当我键入 onClick${getApi()} 时,页面上出现错误:“Object(...) os not a function”
When i type onClick${getApi} there is no error on the page but after clicking on the button nothing happens and when i inspect the code on the page o can see onclick="undefined"当我输入 onClick${getApi} 时,页面上没有错误,但单击按钮后没有任何反应,当我检查页面上的代码时,可以看到 onclick="undefined"
The same happens when I tried "export function getApi(){}" in the JSFunctions.module.js file当我在 JSFunctions.module.js 文件中尝试“export function getApi(){}”时也会发生同样的情况
Let's say getApi
returns "some_result"
for the sake of simplicity.为简单起见,假设
getApi
返回"some_result"
。 Your html will compile to onClick=some_result
.您的 html 将编译为
onClick=some_result
。 That's not valid html and that won't work as you expect.这不是有效的 html 并且不会像您期望的那样工作。
What you're trying to do is call getApi
on button click.您要做的是在单击按钮时调用
getApi
。 That would better be achieved with something along the lines of最好通过以下方式来实现
// define getApi in the global scope so it can be referrenced in the DOM
window.getApi = getAPi;
// reference it in the dom
this.domElement.innetHTML = `...<input onclick="getApi">...`
Don't use an inline onclick
attribute.不要使用内联
onclick
属性。 Attach an event listener to the button.将事件侦听器附加到按钮。
this.domElement.innerHTML = `
<input type="text" id="userEmailInput"><br><br>
<input type="Button" value="Przycisk"><br><br>
<div id="html_BirthdayTable"></div>
`;
document.querySelector('button[value="Przycisk"]').addEventListener("click", getApi);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.