Javascript onload函数未运行

时间:2017-04-12 20:33:31

标签: javascript html function onclick onload

我正试图让标题在“Board Certified Plastic Surgeon,Landon Keith”和“Landon Keith,Board Certified Plastic Surgeon”之间切换,但没有任何事情发生,它看起来像onload功能没有运行

实施例。当我点击图像时,标题显示“Landon Keith,Board Certified Plastic Surgeon”,当我再次点击图像时,应该说“Board Certified Plastic Surgeon,Landon Keith”等等。

我的代码如下:

    var p = document.getElementById('pic');
    var h = document.getElementById('head');
    alert("oh");
    window.onload=function(){
    	alert("inonload");  // This alert function is not showing up
    
    	p.onclick = function(){
    		if (sessionStorage["clicked"] == "true"){
    			alert ("if");
    			sessionStorage["clicked"] = "false";
    			h.innerHTML = "Board Certified Plastic Surgeon, Landon Keith";
    		}else{
    			alert ("else");
    			sessionStorage["clicked"] = "true";
    			h.innerHTML = "Landon Keith, Board Certified Plastic Surgeon";
    		}
    	};
    };
    
    alert("end");
    body{
    	margin-bottom: 100px;
    	margin-right: 20px;
    	margin-left: 20px;
    	margin-top: 10px;
    	background-color: green;
    	font-family:Helvetica;
    }
    
    .navBar {
    	background-colour: red;
    	
    }
    
    #pagewrap {
    	background-color: yellow;
    	height: 280px;
    	width: 640px;
    	margin-left: auto;
    	margin-right: auto;
    	padding-top: 25px;
    }
    
    ul {
    	padding-left: 10px;
    	background-color: red;
    	list-style: none;
    }
    
    ul li {
    	display: inline;
    }
    
    ul li a {
    	text-decoration:none;
    	color:white;
    }
    
    img {
    	float: right;
    	padding-right: 20px;
    }
    
    h1 {
    	margin-left: 25px;
    	font-size: 14pt;
    }
    
    ol {
    	margin-left: 25px;
    }
    
    p {
    	margin-left: 25px;
    }
  <!DOCTYPE html>
    <html>
    <head>
    <title>Keith and Company</title>
    <link rel="stylesheet" type="text/css" href="css.css">
    <script src='js.js'></script>
    </head>
    <body onload="init()">
    	<div id=pagewrap>
    		<img id="pic" src=image.png></img>
    		<ul>
    			<li class="navBarItem"><a href="#3">Reconstructive Surgery</a></li>
    			<li class="navBarItem"><a href="#4">Cosmetic Surgery</a></li>
    			<li class="navBarItem"><a href="#5">Awards</a></li>
    			<li class="navBarItem"><a href="#6">Testimonials</a></li>
    		</ul>
    		
    		<h1 id="head" >Landon Keith, Board Certified Plastic Surgery</h1>
    		<ol>
    			<li> M.D., <a href="#1"> University of SomeState></a></li>
    			<li> Specialization. <a href="#2"> John Hide></a></li>
    		</ol>
    		<p>
    			Keith and Company<BR>
    			111 Street Name<BR>
    			Town, State, Postal Code<BR>
    		</p>
    	</div>
    	
    </body>

1 个答案:

答案 0 :(得分:2)

onload元素上的内联body处理程序将覆盖JavaScript文件中的onload(先前加载)。从onload=init()代码中移除body,您的外部代码就会运行。