让前端飞Web前端之路

JavaScript之事件练习

2019-08-02  本文已影响2人  意蜀

补充以下HTML,实现点击某一个数字可以alert出该数字。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>事件监听</title>
</head>
<body>
<ul id="no">
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
    <li>6</li>
    <li>7</li>
</ul>

<script>
   // write your code here 
   // ......
</script>
</body>
</html>

答案

 var list=document.getElementById('no').getElementsByTagName('li');
    for(var i=0;i<list.length;i++){
         list[i].onclick=function(){
             alert(this.firstChild.nodeValue);//使用dom的nodeValue属性
         }
    }

实现一个基础的计时器应用,点击开始按钮开始计时,点击结束按钮结束计时,并把计时的结果显示在上面的输入框中。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>定时器示例</title>
</head>
<body>

<input type="text" id="result">

<input type="button" value="开始" >
<input type="button" value="结束" >

<script>
    // write your code here
    // ......
</script>
</body>
</html>

答案

  var hello=0;
        var time;
        var go=0;
     function timedCount(){
         document.getElementById('result').value=hello;
         hello=hello+1;
         time=setTimeout(function(){timedCount()},1000);
        }
     function start(){
         if (!go){
            go=1;
             timedCount();
         }
    }
      function stop(){
         clearTimeout(time);
         go=0;
         }

上一篇 下一篇

猜你喜欢

热点阅读