这是我完整的测试 HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Table</title>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="jquery-ui.js"></script>
<script type="text/javascript" src="Untitled_1.js"></script>
</head>
<body>
<div id="sidebar">
<table id="table1">
<tr>
<th>Table</th>
</tr>
<tr>
<td>
<a rel="img1">Link1</a>
</td>
<td>
<a rel="img2">Link2</a>
</td>
</tr>
</table>
</div>
<div id="box">
<img src="cant-believe-it-icon.png" id="img1"/>
<img src="too-much-icon.png" id="img2"/>
</div>
</body>
</html>
这个测试页面没有CSS,这里是整个.js文件:
$('a').click(function(){
imgid = $(this).attr('rel');
$('a').removeClass('active');
$(this).addClass('active');
$('img').hide();
$('#'+imgid).fadeIn('slow');
});
当它在 jsfiddle 中运行时(没有 head、body、html 标签等)它工作正常——当其中一个被点击时,一个图像显示而另一个不显示。但是,当将整个代码放入 microsoft expressions web 并进行预览时,单击链接时没有任何反应。这是我将 .js 文件链接到 html 的问题吗?我应该如何解决这个问题?
最佳答案
在 body
标记的末尾加载您的脚本,或将您的代码放在窗口 onload 事件中。
$(function() {
$('a').click(function(){
imgid = $(this).attr('rel');
$('a').removeClass('active');
$(this).addClass('active');
$('img').hide();
$('#'+imgid).fadeIn('slow');
});
})
A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute. Code included inside $( window ).load(function() { ... }) will run once the entire page (images or iframes), not just the DOM, is ready.
关于javascript - 创建随其他对象 onclick 变化的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23170582/