2017-01-14 50 views
1

我无法让我的简单JavaScript代码运行,我在考虑代码可能无法正确链接。你会友善地看一看吗?下面是HTML代码:将Javascript链接到HTML

<!DOCTYPE html> 
<html> 
<head> 
    <title>Jiggle Into JavaScript</title> 
    <script type="text/javascript" src="javascript.js"></script> 

    <!-- <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> --> 

</head> 
<body> 

    <p>Press the buttons to change the box!</p> 

    <div id="box" style="height:150px; width:150px; background-color:orange; margin:25px"></div> 

    <button id="Button1">Grow</button> 
    <button id="Button2">Blue</button> 
    <button id="Button3">Fade</button> 
    <button id="Button4">Reset</button> 

</body> 
</html> 

而这里的JS代码:

document.getElementById("Button1").addEventListener("click", function(){ 

    document.getElementById("box").style.height=200%; 

}); 

感谢您的帮助,您可以提供!

+3

您需要加载JS ** **后用ID的元素'Button1' –

回答

0
  1. 添加你的脚本,你的身体结束

    <body> 
        ... 
        <script src="some.js"></script> 
    </body> 
    
  2. 200%应该是一个字符串( “200%”)

    document.getElementById("box").style.height = "200%"; 
    
0

试试这个:

document.addEventListener('DOMContentLoaded', function(){ 
    document.getElementById("Button1").onclick = function(){ 
     document.getElementById("box").style.height='200px'; 
     //document.getElementById("box").style.height='200%'; 
    }; 
}, false); 

我将您的代码包装在DOMContentLoaded中,所以代码将在页面(文档)完全加载后生效。我也对你的点击功能做了一些小的改动。

2

有3个问题:

  1. 在JavaScript中,没有200%,JS比CSS不同。 JS使用整数和字符串。如果您想将元素的高度设置为200%,你需要给它一个字符串类型:

    document.getElementById("box").style.height="200%"; 
    
  2. 你的js文件加载和按钮加载之前如此执行。因此document.getElementById("Button1")不会返回该元素,并且您无法将事件侦听器绑定到该元素,因此当您单击该按钮时,没有任何操作。您有两种选择:

    2.1添加DOMContentLoaded listener to the window或使用jQuery's .ready()。如果你这样做,你的代码将在每个HTML元素被加载后执行,因为浏览器首先下载HTML文件并构建DOM。完成后,你将能够找到你的按钮,并添加监听器。

    2.2正如其他人所说,在</body>标记之前的每个HTML元素之后加载您的JavaScript。由于它在每个元素被加载后执行,这也会起作用。但是,通常,我们在内容之后加载JS文件以获得更好的优先,而不是因为我们不想添加窗口加载侦听器。

  3. 200%可能无法正常工作。我想你想把盒子的高度加倍,对吧?用给定的百分比设置高度并不等于缩放它。尺寸百分比是神奇的,它们与它们的父元素有关,在你的情况下它可能不像你所能工作的那样。你应该试试这个:

    var box = document.getElementById("box"); 
    box.style.height = (parseInt(box.style.height) * 2) + "px";