简体   繁体   中英

Is it possible to append data into a html element using DOM in Javascript?

I have looked for duplicate questions, however many refer to adding data to XML please forgive me if I have missed something here but I need some help

so far I have this:

html page

<!DOCTYPE html>
<html>
<head>
<title>Template</title>
<script type="text/javascript" src="script/controlpanelAdmin.js"></script>
<script type="text/javascript" src="script/controlpanelModerator.js"></script>
<script type="text/javascript" src="script/jquery-1.12.0.js"></script>
<link rel="stylesheet" href="script/css.css" />
</head>
<body>
<fieldset id="control_panel">
<legend>Control Panel</legend>
</fieldset>

<p id="content"> Content </p>

</body>
</html>

controlpanelAdmin.js

window.onload = function() {

var controlpanel = document.getElementById("control_panel");
var para = document.createElement("p");
var att = document.createAttribute("admin");
var br = document.createElement("br");
var txt = document.createTextNode("Admin Control Panel");



controlpanel.appendChild(para);
para.setAttribute("id", att);
para.appendChild(txt);
para.appendChild(br);
}

controlpanelModerator.js

window.onload = function() {

var controlpanel = document.getElementById("control_panel");
var para = document.createElement("p");
var att = document.createAttribute("mod");
var br = document.createElement("br");
var txt = document.createTextNode("Moderator Control Panel");



controlpanel.appendChild(para);
para.setAttribute("id", att);
para.appendChild(txt);
para.appendChild(br);
}

When the page loads, 'Admin Control Panel' is written into the fieldset tag but is then replaced by: 'Moderator Control Panel'

I cannot for the life of me think how to append both lines (and maybe other data as well) into one element

When the page loads, 'Admin Control Panel' is written into the fieldset tag but is then replaced by: 'Moderator Control Panel'

That can't happen. Admin Control Panel should never appear in the page.

  1. script/controlpanelAdmin.js loads. It causes a value to be assigned to window.onload .
  2. script/controlpanelModerator.js loads. It causes that value to be overwritten with a new one.
  3. The page finishes loading
  4. The load event fires
  5. The function defined in script/controlpanelModerator.js is called

Don't assign values to window.onload . Use addEventListener instead.

addEventListener("load", function () { ... });

You've got two onload functions competing. Can you merge them into one function?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM