欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

前端学习5(html dom)(JSON)

程序员文章站 2024-03-20 10:20:40
...

找寻方法

document.getElementById(id)
document.getElementsByTagName(name) var x = document.getElementsByTagName("p");
document.getElementById("demo").innerHTML = 
'The first paragraph (index 0) is: ' +x[2].innerHTML;
document.getElementsByClassName(name)
var myNodeList = document.querySelectorAll("p");  //找寻所有子节点

处理方法

document.write();

document.getElementById(id).innerHTML="hello";

document.getElementById("myImage").src ="landscape.jpg";  //change attribute

document.getElementById("p2").style.color ="blue"; //change css

<h1 onclick="this.innerHTML = 'Ooops!'">Click on this text!</h1>

对节点的定义

  • parentNode
  • childNodes[nodenumber]
  • firstChild
  • lastChild
  • nextSibling
  • previousSibling


节点属性

document.getElementById("id01").nodeName

document.getElementById("id01").nodeType

document.getElementsByTagName("p").length

ELEMENT_NODE 1 <h1 class="heading">W3Schools</h1>
ATTRIBUTE_NODE 2  class = "heading" (deprecated)
TEXT_NODE 3 W3Schools
COMMENT_NODE 8 <!-- This is a comment -->
DOCUMENT_NODE 9 The HTML document itself (the parent of <html>)
DOCUMENT_TYPE_NODE 10 <!Doctype html>
添加节点

<script>
var para = document.createElement("p");
var node = document.createTextNode("This is new.");
para.appendChild(node);   //append the text node to the <p> element:
var element = document.getElementById("div1");
element.appendChild(para);
</script>
JSON

JavaScript Object Notation(for stroage and exchange data)  json就是一个text,也可以理解为string

JSON uses JavaScript syntax, but the JSON format is text only.
Text can be read and used as a data format by any programming language.

成对出现,“”括起,{}括起object []array


与xml区别:
 XML has to be parsed with an XML parser. JSON can be parsed by a standard JavaScript function. (更快read write,short)
可以在object中套用object(myObj.cars["car2"]  //   myObj.cars.car2)如果cars是array 用myObj.cars[2]

myObj = {"name":"John","age":30, "car":null };
x = myObj.name;
x = myObj["name"];

for (xin myObj) {
    document.getElementById("demo").innerHTML+= x; //输出 name,age car
    document.getElementById("demo").innerHTML+= myObj[x];  //输出 john 30 null

JSON.parse() to convert text into a JavaScript object:
var arr = ["John", "Peter","Sally", "Jane" ];
var myJSON = JSON.stringify(arr);  //将js转化为json



request JSON from the server by using an AJAX request //利用XMLHttpRequest