使用纯JavaScript的Javascript onclick事件处理 [英] Javascript onclick event handling with pure JavaScript
问题描述
所以这是非常简单的,但我仍然是JavaScript的新手,只是找到了jsfiddle。我试图找到元素与getElementById()来禁用并启用一个按钮。我缺少什么?
So this is really straight forward but I'm still fairly new at JavaScript and just found jsfiddle. I'm trying to find the element with the getElementById() to disable and enable a button. What am I missing?
<form name="frm" >
<div id="chkObj">
<input type="checkbox" name="setChkBx" onclick="basicList.modifyAndEnableButton(this)" ></input>
</div>
<div id="Hello">
<input type="button" name="btn" value="Hello" ></input>
</div>
这是一个列表,正在使用添加复选框,因为将有多个
This is a list that I am using to add checkboxs because there is going to be more than one
var basicList = {
'items':{},
'modifyAndEnableButton':function(obj1) {
var element = document.getElementsByName("btn");
if(obj1.checked == true && element.getAttribute('disabled') == false){
element.getAttribute('disabled') = true;
this.addRecord(obj2);
} else if(element.getAttribute('disabled') == true) {
if(hasItems == false) {
element.getAttribute('disabled') = false;
}
}
}
};
http://jsfiddle.net/Arandolph0/E9zvc/3/
提前感谢您的帮助。
推荐答案
所有浏览器都支持此功能(在此处的示例):
All browsers support this (see example here):
mySelectedElement.onclick = function(e){
//your handler here
}
然而,有时你想要添加一个处理程序(而不是改变一个),更普遍的情况是可用的,你应该使用 addEventListener
(需要垫片为IE8 - )
However, sometimes you want to add a handler (and not change the same one), and more generally when available you should use addEventListener
(needs shim for IE8-)
mySelectedElement.addEventListener("click",function(e){
//your handler here
},false);
这是一个工作示例:
var button = document.getElementById("myButton");
button.addEventListener("click",function(e){
button.disabled = "true";
},false);
和html:
<button id='myButton'>Hello</button>
(fiddle)
以下是一些有用的资源:
(fiddle)
Here are some useful resources:
-
addEventListener
on mdn - DOM中的点击事件规格
- 点击示例在MDN JavaScript教程中
addEventListener
on mdn- The click event in the DOM specification
- Click example in the MDN JavaScript tutorial
这篇关于使用纯JavaScript的Javascript onclick事件处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!