我正在撰写一个Javascript,当点击一个链接时,它会在div
中显示内容。代码如下。
场景是这样的,我有10个锚标签,当我点击一个锚时,它应该以div textResult
function getTheIncident(keyWord, text, shortDesc, description) {
console.log(keyWord + "\t" + text);
var e = document.getElementById('textResult');
var issueTag = document.createElement('H2');
var resolutionTag = document.createElement('H2');
var descTag = document.createElement('H2');
if (text) {
var issue = document.createElement('div');
issueTag.innerHTML = "Issue";
issue.innerHTML = shortDesc.replace('\^', '\'');
issue.insertBefore(issueTag, issue.firstChild);
var resol = document.createElement('div');
resolutionTag.innerHTML = "Resolution";
resol.innerHTML = text.replace('\^', '\'');
resol.insertBefore(resolutionTag, resol.firstChild);
var desc = document.createElement('div');
descTag.innerHTML = "Description";
desc.innerHTML = description.replace('\^', '\'');
desc.insertBefore(descTag, desc.firstChild);
e.insertBefore(resol, e.firstChild);
e.insertBefore(desc, e.firstChild);
e.insertBefore(issue, e.firstChild);
}
else {
h1Tag.innerHTML = "Issue";
e.innerHTML = shortDesc.replace('\^', '\'');
e.insertBefore(h1Tag, e.firstChild);
h1Tag.innerHTML = "Description";
e.innerHTML = shortDesc.replace('\^', '\'');
e.insertBefore(h1Tag, e.firstChild);
h1Tag.innerHTML = "No Resolution Available";
e.innerHTML = text.replace('\^', '\'');
e.insertBefore(h1Tag, e.firstChild);
}
}
这是我第一次点击时得到如下结果。
Issue
Laptop issue
Description
RAM with 128GB
Resolution
A Procurement order has been placed for a new RAM with 128 GB
当我第二次点击时
Issue
Laptop issue
Description
RAM with 128GB
Resolution
A Procurement order has been placed for a new RAM with 128 GB
Issue
Laptop issue
Description
RAM with 128GB
Resolution
A Procurement order has been placed for a new RAM with 128 GB
但我希望这只能出现一次。
请让我知道我哪里出错了,我该怎么办呢。
注意我正在使用Javascript,而不是使用任何jQuery。
由于
答案 0 :(得分:0)
您必须在添加新孩子之前删除旧孩子,否则您将同时拥有两个孩子。
var issue, resol, desc;
if (text) {
if (issue) e.removeChild(issue);
if (resol) e.removeChild(resol);
if (desc) e.removeChild(desc)
issue = document.createElement('div');
issueTag.innerHTML = "Issue";
issue.innerHTML = shortDesc.replace('\^', '\'');
issue.insertBefore(issueTag, issue.firstChild);
resol = document.createElement('div');
resolutionTag.innerHTML = "Resolution";
resol.innerHTML = text.replace('\^', '\'');
resol.insertBefore(resolutionTag, resol.firstChild);
desc = document.createElement('div');
descTag.innerHTML = "Description";
desc.innerHTML = description.replace('\^', '\'');
desc.insertBefore(descTag, desc.firstChild);
e.insertBefore(resol, e.firstChild);
e.insertBefore(desc, e.firstChild);
e.insertBefore(issue, e.firstChild);
}
这不是最佳解决方案