自动化测试学习之路--json、dom编程

1.json:

json是JavaScript Object Notation,是一种数据传输格式。

以下程序都是在浏览器的Console下执行的。

创建一个javaScript的对象:

var student={
 id:'10001',
 name:'claire',
 loveSport:['pingpang','run','yoga'],
 
};

之后将其序列化为json格式的数据:

var jsonStu=JSON.stringify(student);

此时输出jsonStu为:"{"id":"10001","name":"claire","loveSport":["pingpang","run","yoga"]}"

这种格式的不好看,可以加上几个参数:

JSON.stringify(student,['id','name'],' ');

输出结果为(与我们在平时测试见到的格式相同):"{
 "id": "10001",
 "name": "claire"
}"

 还可以将Json格式数据反序列化为一个javaScript的对象。

JSON.parse();

想了解更多关于反序列化的内容,可以到菜鸟教程上学习下。网址:http://www.runoob.com/js/javascript-json-parse.html

2.方法

function add(a,b){
 alert(a+b);
}
add(10,20);

声javaScript中,参数不需要声明形参类型、返回值类型。直接用function 方法名(形参1,形参2){方法体}
 
3.dom编程
dom是 document Object Model,文档对象模型。
简单来说,当我们打开一个网页,页面加载完成后,浏览器就会自动创建该页面的dom(文档对象模型,就是该页面的一个对象),通过该对象就可以访问该页面的所有元素。
我们做web自动化测试的时候,通常需要捕获到某个元素,并对其进行操作。其原理就是通过dom模型(网页对象)去获取所要捕获的元素。
 
下面讲一下用js来获取并操作html的元素。
浏览器上打开一个窗口,首先是会生成一个wondows的对象。是JavaScript中的顶层对象,是document的父节点。代表是在浏览器上打开了一个窗口。
 
document是代表窗口中显示的页面,表示当我们打开一个网页,网页内容加载完毕后。是windows的子节点。通过该节点可以遍历到html中的所有子节点。对应的事件是:wondows.onload如果该时间完成后你需要完成一系列的操作,此时就需要为该事件注册一个方法。
注册方式为:
 <script>
 window.onload=function (){
 var a=document.getElementById('10001');
 alert(a);

        }
</script>
我们自己创建了一个html文件,其中有输入框的id为10001。上面就获取到了该元素,并弹框显示了该元素。
其中:
document.getElementById(''),
(method) Document.getElementById(elementId: string): HTMLElement

Returns a reference to the first object with the specified value of the ID or NAME attribute.

可以看到返回的是一个对象的引用。当我们想获取到该对象的value值时,可以用a.value即可

还有其他方式可获取元素:

举例:

  alert(document.getElementsByClassName('class1')[0].value);
  alert(document.getElementsByClassName('class1').length);
  alert(document.getElementsByTagName('input')[1].value);
  alert(document.getElementsByTagName('input').length);

还可以获取到超链接(a标签)中的文字和html:

console.log(document.getElementById('10002').innerText);
console.log(document.getElementById('10002').innerHTML);

 其他事件的常用事件:

     
  a.onblur=function(){
       alert('失去焦点')

           }

           a.onfocus=function(){
            alert('聚焦')

           }

           a.onchange=function(){
            alert('内容改变')

           }
 
            a.onclick=function(){
                alert('点击事件')

            }

            a.ondblclick=function(){
                alert('双击事件')
            }

            a.onmouseover=function(){
                alert('鼠标上浮事件')
            }
原文地址:https://www.cnblogs.com/clairejing/p/9224741.html