创建随其他对象单击而更改的图像

Creating images that change with other object onclick

本文关键字:图像 单击 其他 对象 创建      更新时间:2023-09-26

这是我完整的测试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标记等),它运行得很好——当点击其中一个时,一个图像会显示,而另一个则不会。然而,当整个代码被放在microsoftexpressionsweb中并预览时,单击链接时不会发生任何事情。这是我将.js文件链接到html的问题吗?我该怎么解决这个问题?

body标记的末尾加载脚本,或者将代码放在窗口onload事件中。

$(function() {
    $('a').click(function(){
      imgid = $(this).attr('rel');
      $('a').removeClass('active');
      $(this).addClass('active');
      $('img').hide();    
      $('#'+imgid).fadeIn('slow');
    });
})

来自jQuery文档

在文档"准备就绪"之前,无法安全地操作页面jQuery为您检测这种准备状态。内部包含代码$(document).ready()将只运行一次页面document Object模型(DOM)已准备好执行JavaScript代码。包含的代码在$(window)内。load(function(){…})将运行一次页面(图像或iframe),而不仅仅是DOM,已经准备好了。