Javascript 我似乎无法让这个简单的代码工作

Javascript 我似乎无法让这个简单的代码工作,javascript,html,Javascript,Html,这意味着在按钮下方加载图像。每个按钮加载相同的图像,但具有不同的属性。就像这个例子中的颜色一样 <html> <head> <script type="text/javascript"> $(document).ready(function () { $("button").click(function () { var imgUrl = $(this).data('rel'); $("#area").html("<

这意味着在按钮下方加载图像。每个按钮加载相同的图像,但具有不同的属性。就像这个例子中的颜色一样

<html>
<head>
<script type="text/javascript">
$(document).ready(function () {
    $("button").click(function () {
        var imgUrl = $(this).data('rel');
        $("#area").html("<img src='" + imgUrl + "' alt='description' />");
    });
});
</script>
</head>
<body>
<table border="1">
    <tr>
        <td>
            <button data-rel="http://i.imgur.com/icb4onK.jpg">Blue</button>
        </td>
        <td>
            <button data-rel="http://i.imgur.com/3mSS06v.jpg">Red</button>
        </td>
        <td>
            <button data-rel="http://i.imgur.com/Su3Rtoy.jpg">Green</button>
        </td>
    </tr>
</table>
<table>
    <tr>
        <td>
            <div id="area"></div>
        </td>
    </tr>
</table>
</body>
</html>
这在这里起作用:

但是,当我将Microsoft记事本文件保存为test.html时,我确实选择了所有文件类型,它只会加载按钮。按钮不起作用。我不知道这是我如何添加JavaScript的问题,还是我的浏览器的问题。我在用谷歌浏览器


我还想知道这段代码是否可以在网站上的HTML应用程序中使用。

您的代码中缺少jQuery库

在标签前添加以下内容:

如果您喜欢jQuery的本地副本,请从下载并将其添加到您的项目中。然后使用以下代码:

<script src="path/to/jquery.min.js"></script>

您可能希望在脚本之前包含jQuery。JSFiddle可以为您做到这一点,但在您的独立版本上,您应该自己做到这一点

将其放在您自己的脚本标记之前:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

或者从您自己的位置导入jQuery

您必须添加jQuery库,如下所示,这在JSFIDLE示例中提供

<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.3.min.js"></script>

您没有包括jQuery,这是一件好事,因为这里不需要jQuery

您可以在不使用jQuery的情况下实现相同的功能,如下所示:

window.addEventListener('load', function() {
    // Create the image
    var img = new Image();
    // And put it in the document
    document.getElementById('area').appendChild(img);

    // Find all the buttons in the document...
    [].forEach.call(document.querySelectorAll('button'), function(button) {
        // Add a click handler on each
        button.addEventListener('click', function(e) {
            // To change the src of the image
            img.src = this.dataset.rel;
        });
    });
});
如果您坚持使用jQuery,请查看其他答案,它们会告诉您如何在文档中包含jQuery

它在JSFIDLE中工作的原因是您已经在设置中包含了它


看起来您试图在不包含jQuery的情况下使用jQuery函数。非常感谢,这已经解决了这个问题。
window.addEventListener('load', function() {
    // Create the image
    var img = new Image();
    // And put it in the document
    document.getElementById('area').appendChild(img);

    // Find all the buttons in the document...
    [].forEach.call(document.querySelectorAll('button'), function(button) {
        // Add a click handler on each
        button.addEventListener('click', function(e) {
            // To change the src of the image
            img.src = this.dataset.rel;
        });
    });
});