javascript - 创建随其他对象 onclick 变化的图像

标签 javascript jquery html css

这是我完整的测试 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');
    });
})

From jQuery docs

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/

相关文章:

javascript - 如何模拟 angularjs $resource 工厂

JavaScript:在字符串中搜索字符串

javascript - 如何用自定义函数替换javascript原型(prototype)

javascript - jQuery 找不到自定义标签

javascript - Ajax获取输入文本框数组并将结果显示到div

html - 在媒体查询中使用 min 和 max-width 有什么实际区别吗?

javascript - 使用 jQuery 选择不相关的元素

javascript - 读取下一页的文本区域值。存储下一页的值

javascript - 一次将事件绑定(bind)到多个元素时,每个元素的新实例?

javascript - 动态更新 CSS