????:<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>留言信息作業(yè)</title> <style type="t
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>留言信息作業(yè)</title>
<style type="text/css">
*{margin:0px;padding:0px;}
body{background:#ccc;}
.top{width:800px;height:48px;background-color:black;margin:0px auto;}
.top-text{display:block;font-size:22px;line-height:48px;font-weight:bold;text-align:center;color:#fff}
.liuyan{width:800px;height:48px;position: relative;margin:0px auto;top:10px;}
.ly-text{width:580px;height:44px;font-size:22px;}
.bt{width:200px;height:48px;line-height:48px;position: absolute;left:600px;}
.ly-xs{width:800px;background:black;height:800px;position: relative;margin:0px auto;top:30px;text-align:center;}
.ly-ts{color:limegreen;font-size:22px;font-weight:bold;}
ul{list-style: none;}
ul li{font-size:20px;font-weight:bold;color:limegreen;position: relative;margin:10px auto;}
</style>
</head>
<body>
<div class="top"><span class="top-text">在線留言內(nèi)容作業(yè)</span></div>
<div class="liuyan">
<input type="text" name="info" class="ly-text">
<button class="bt">提交留言內(nèi)容</button>
</div>
<div class="ly-xs">
<span class="ly-ts">下方為顯示留言的內(nèi)容</span>
<ul></ul>
</div>
<script type="text/javascript">
let input=document.children[0].children[1].children[1].children[0]
let button=document.children[0].children[1].children[1].children[1]
let ul=document.children[0].children[1].children[2].children[1]
button.onclick=function(){
let li=document.createElement('li');
li.innerHTML=input.value;
ul.appendChild(li)
input.value='';
}
</script>
</body>
</html>
雖然功能實(shí)現(xiàn)了 但是老師 我想問下 我用了children的方法才獲取到了div下的需要的元素 開始我直接用選擇器的方法 為什么獲取不到div下的input框以及按鈕等等需要的元素呢?
還有一個(gè)問題,如果要獲取到頁面中的元素 一定要把js代碼放到body代碼中創(chuàng)建的元素的下面嘛?我開始放在head頭部一樣獲取不到 后來發(fā)現(xiàn)連body都獲取不到
?? ???:韋小寶?? ??:2019-02-28 09:12:06
???? ??:首先是第一個(gè)問題 你通過選擇器的方式是可以直接獲取到對(duì)應(yīng)的元素啊
第二個(gè)問題 因?yàn)樵诖a運(yùn)行的過程中 是從上到下運(yùn)行的 把js放在head中還沒等需要的標(biāo)簽實(shí)現(xiàn) js就已經(jīng)跑過了 不過你要是寫成方法也就可以了