我是HTML <Javascript概念的新手。 所以请好好放轻松我。 我创建了2个标签,并希望使用它们的ID,onload有选择地为每个div标签添加数据,但下面的代码没有为每个div标签添加“H1”和“h2”。 我错过了什么 ?
<html> <head> <title>Titlehere</title> <p> Hello></p> </head> <body> <div id="tab1" onload="populatehtmlTab1()"> <p>i1</p> </div> <div id="tab2" onload="populatehtmlTab2()"> <p>i2</p> </div> <script type="text/javascript"> function populatehtmlTab1() { document.getElementById(tab1).innerHTML = document.getElementById(tab1).innerHTML + "<p>h1</p>"; } function populatehtmlTab2() { document.getElementById(tab2).innerHTML = document.getElementById(tab1).innerHTML + "<p>h2</p>"; } </script> </body> </html>I'm very new to HTML< Javascript concepts. So kindly go easy on me. I created 2 tags & want to selectively add data to each div tag using their ID, onload, but the the below code isn't adding "H1" & "h2" to each div tag. Did i miss something ?
<html> <head> <title>Titlehere</title> <p> Hello></p> </head> <body> <div id="tab1" onload="populatehtmlTab1()"> <p>i1</p> </div> <div id="tab2" onload="populatehtmlTab2()"> <p>i2</p> </div> <script type="text/javascript"> function populatehtmlTab1() { document.getElementById(tab1).innerHTML = document.getElementById(tab1).innerHTML + "<p>h1</p>"; } function populatehtmlTab2() { document.getElementById(tab2).innerHTML = document.getElementById(tab1).innerHTML + "<p>h2</p>"; } </script> </body> </html>最满意答案
这有一些问题。 这是修改后的代码:
function populatehtmlTab1() { document.getElementById('tab1').innerHTML = "<p>h1</p>"; } function populatehtmlTab2() { document.getElementById('tab2').innerHTML = "<p>h2</p>"; } function loadHtml(){ populatehtmlTab1(); populatehtmlTab2(); }<html> <head> <title>Titlehere</title> <p> Hello></p> </head> <body onload="loadHtml()"> <div id="tab1" > <p>i1</p> </div> <div id="tab2"> <p>i2</p> </div> <script type="text/javascript"> </script> </body> </html>首先,元素id选择器必须是一个字符串:
document.getElementById('tab1')第二,你只需要直接分配innerHTML:
document.getElementById('tab2').innerHTML = "<p>h2</p>";第三,你应该在主体上使用onload ,我将你的函数包装到修改后的代码中的另一个函数中。
There are a few things wrong with this. Here is the code amended:
function populatehtmlTab1() { document.getElementById('tab1').innerHTML = "<p>h1</p>"; } function populatehtmlTab2() { document.getElementById('tab2').innerHTML = "<p>h2</p>"; } function loadHtml(){ populatehtmlTab1(); populatehtmlTab2(); }<html> <head> <title>Titlehere</title> <p> Hello></p> </head> <body onload="loadHtml()"> <div id="tab1" > <p>i1</p> </div> <div id="tab2"> <p>i2</p> </div> <script type="text/javascript"> </script> </body> </html>First the element id selector must be a string:
document.getElementById('tab1')second you just need to assign the innerHTML directly:
document.getElementById('tab2').innerHTML = "<p>h2</p>";Third you should use onload on the body, I wrapped both your functions into another function in my amended code.
更多推荐
发布评论