[英]How to run a onClick function inside inner HTML in Class Javascript?
I'm having trouble using Class Javascript.我在使用 Class Javascript 时遇到问题。 so I want to pass the looped project id.
所以我想传递循环的项目ID。 How do I execute onClick with the
handleProject
function?如何使用
handleProject
function 执行 onClick? for test I use alert
.对于测试,我使用
alert
。 The following code produces an "unexpected end of input" error以下代码产生“输入意外结束”错误
import axios from "axios";
export class ProjectPanel extends DockingPanel {
constructor(viewer, container, id, title, options, projects) {
super(container, id, title, options);
this.viewer = viewer;
this.options = options;
// docking panel
this.container.classList.add("docking-panel-container-solid-color-a");
this.container.style.cssText = `
top: 10px;
left: 10px;
width: 300px;
padding: 10px;
min-height: 300px;
resize: auto;
`;
this.projects = projects;
if (this.projects) {
this.updateProjectList(this.projects);
}
}
updateProjectList(projects) {
console.log(projects);
this.containerProject = document.createElement("div");
this.containerProject.className = "containerProject";
this.container.append(this.containerProject);
if (projects) {
this.containerProject.innerHTML =
"<div >" +
projects
.map((project) => {
return (
`<div class='button-bee-project glyphicon glyphicon-triangle-right' onclick=${this.handleProject(project.id)}>` +
project.name +
"</div>"
);
})
.join("") +
"</div>";
} else {
this.containerProject.innerHTML = `
<div>Please Login</div>
`;
}
}
handleProject(id) {
alert(`HELLO ${id}`);
}
}
A simple solution could be to change your structure to append project
to the containerProject
, instead of setting the innerHTML
of containerProject
by string you can create DOM
element, set element's onclick
, and then append it to the containerProject
, like below example:一个简单的解决方案可能是将您的结构更改为 append
project
到containerProject
,而不是通过字符串设置containerProject
的innerHTML
您可以创建DOM
元素,设置元素的onclick
,然后 Z9516DFB15F51C7EE19A4B 到下面的示例containerProject
项目
updateProjectList(projects) {
this.containerProject = document.createElement("div");
this.containerProject.className = "containerProject";
this.container.append(this.containerProject);
if (projects) {
this.containerProject.innerHTML = '<div></div>';
const projects = this.containerProject.firstElementChild;
projects.forEach((project) => {
const projectEl = document.createElement('div');
projectEl.innerHTML = project.name;
projectEl.className = 'button-bee-project glyphicon glyphicon-triangle-right';
projectEl.onclick = ()=> this.handleProject(project.id);
projects.append(projectEl);
});
} else {
this.containerProject.innerHTML = `
<div>Please Login</div> `;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.