这是一个更好的写法,稍作改进。
- 最好将javascript写在头上。
- 通过定义载入后的各种元素,您可以更快速地访问它们。
- 也不提示内联javascript,不要在js里面写html属性。
然后谈论你的错误:
function
不Function
document.getElementById('radius')
应该document.getElementById('radius').value
<html>
<head>
<script>
var radiusBox,sumBox,button;
function my(){
sumBox.innerHTML=radiusBox.value*2
// the use of textContent is more appropiate but works only on newer browsers
}
window.onload=function(){
radiusBox=document.getElementById('radius');
sumBox=document.getElementById('sum');
button=document.getElementById('button');
button.onclick=my
}
</script>
</head>
<body>
<form id="ty">
Give radius:<input type="number" id="radius">
</form>
<p id="sum">Enter a number</p>
<button id="button">Click on me</button>
</body>
</html>
写它这种方式,与任何支持JavaScript的每一个浏览器兼容,一更新的正确方法是使用addEventListener
添加load
和click
处理程序因此也允许您添加多个事件处理程序,但旧的ie不会work.also textContent可能有prblems ...
DEMO
http://jsfiddle.net/frma0zup/
,如果您有任何问题,只是问。
不,你不知道。你得到'错误ReferenceError:我没有定义'。 – Quentin 2014-09-06 17:43:07
语法错误 - 删除一个输入。 – 2014-09-06 17:45:34
不,我得到“NaN” – 2014-09-06 17:46:36