【发布时间】:2015-11-13 18:30:12
【问题描述】:
对于一个概要网络应用程序,我试图在您单击时更改图像。我已经编写了如下代码(在 jsp 文件中),但我想将 JavaScript 与 HTML 分开(下一个代码运行良好):
<head>
<script type='text/javascript'>
function ChangeState(){
if(document.getElementById('imageStateBlue')!=null){
var img=document.getElementById('imageStateBlue');
img.setAttribute('alt', 'State: red');
img.setAttribute('id', 'imageStateRed');
img.setAttribute('src', 'pages/synoptique/src/images/red.png');}
else{
if(document.getElementById('imageStateRed')!=null){
var img=document.getElementById('imageStateRed');
img.setAttribute('alt', 'State: blue');
img.setAttribute('id', 'imageStateBlue');
img.setAttribute('src', 'pages/synoptique/src/images/blue.png');}}}
</script>
</head>
<body>
<img alt='State: blue' id='imageStateBlue' onclick='ChangeState()' src='pages/synoptique/src/images/blue.png'/>
</body>
所以,我尝试了(在 ChangeState.js 中使用相同的 js 代码)(下一个代码不能正常工作):
<head>
<script type='text/javascript' src='pages/synoptique/js/ChangeState.js'></script>
</head>
<body>
<img alt='State: blue' id='imageStateBlue' onclick='ChangeState()' src='pages/synoptique/src/images/blue.png'/>
</body>
以及(这两个接下来的代码不能很好地工作):
<head>
<script type='text/javascript' src='pages/synoptique/js/ChangeState.js'></script>
</head>
<body>
<img alt='State: blue' id='imageStateBlue' src='pages/synoptique/src/images/blue.png'/>
</body>
像这样使用 ChangeState.js:
function toRed(){
var img=document.getElementById('imageStateBlue');
img.setAttribute('alt', 'State: red');
img.setAttribute('id', 'imageStateRed');
img.setAttribute('src', 'pages/synoptique/src/images/red.png');}
function toBlue(){
var img=document.getElementById('imageStateRed');
img.setAttribute('alt', 'State: blue');
img.setAttribute('id', 'imageStateBlue');
img.setAttribute('src', 'pages/synoptique/src/images/blue.png');}
function imgClick(){
document.getElementById('imageStateBlue').addEventListener('click', toRed, true);
document.getElementById('imageStateRed').addEventListener('click', toBlue, true);}
window.addEventListener('load', imgClick, true);
但没有任何效果。它似乎没有在页面加载时导入。 (当代码不能正常工作时,我的意思是点击时图像不会改变)。
【问题讨论】:
标签: javascript html dom javascript-events onclick