html页面上的两个javascript代码不起作用

时间:2016-08-07 18:46:10

标签: javascript html

我写了两个函数,第一个必须用id“希望”扩展文章 第二个应该使图像blobfish消失,但它不起作用,我不知道为什么。我希望你能帮助我。

<!doctype html>
<html>
  <head>
    <style>
      .hidden {display:none;}
    </style>
 </head>
 <body>
   <p id="hope">My hope for you this year is that you will become a good                 problem solver.  
   <a href="javascript:void(0);" onClick="expandArt();">Click</a>
  </p>
 <img src="my_image/blobfish.jpg" id="ugly" onClick="makeInvisible();">
   <script type="text/javascript">
     function expandArt() {
      var expand = "My hope for you this year is that you will become a good  problem solver. Everyone will learn that they can figure out some tough answers  even when they feel stumped and frustrated in math, or reading, or at recess. Instead of giving up, you will say in your own mind, I can figure this out! I can do this.That's my hope for you.";
      document.getElementById("hope").innerHTML = expand;
}

  function makeInvisible() {
      document.getElementById("ugly").className = "hidden"; 
}

  </script>
 </body>
</html>

1 个答案:

答案 0 :(得分:-1)

我已经编写了一个上面设置的工作示例,但是使用了不显眼的javascript 方法。 (即。所有脚本仍保留在<script> </script>标记之间,并与标记的其余部分分开,而不是分散在整个html中。)

function expandArticle() {
    var expandedText = 'My hope for you this year is that you will become a good  problem solver. Everyone will learn that they can figure out some tough answers even when they feel stumped and frustrated in math, or reading, or at recess. Instead of giving up, you will say in your own mind, I can figure this out! I can do this. That\'s my hope for you.';
    this.parentNode.innerHTML = expandedText;
}

function makeInvisible() {
    this.classList.add('hidden'); 
}

var hope = document.getElementsByClassName('hope')[0];
var hopeAnchor = hope.getElementsByTagName('a')[0];
hopeAnchor.addEventListener('click',expandArticle,false);

var ugly = document.getElementsByClassName('ugly')[0];
ugly.addEventListener('click',makeInvisible,false);
.hidden {
display:none;
}

.hope a {
font-weight: bold;
text-decoration: underline;
cursor: pointer;
}
<p class="hope">My hope for you this year is that you will become a good problem solver.  
<a>Click</a>
</p>

<img class="ugly" src="http://placehold.it/140x140" />