Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
448 views
in Technique[技术] by (71.8m points)

html - Handling "onclick" event with pure JavaScript

This is really straight forward but I'm still fairly new to 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>
</form>

This is a list that I am using to add checkboxes 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/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

All browsers support this (see example here):

mySelectedElement.onclick = function(e){
    //your handler here
}

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);

Here is a working example:

var button = document.getElementById("myButton");
button.addEventListener("click",function(e){
    button.disabled = "true";
},false);

And html:

<button id='myButton'>Hello</button>

(fiddle)

Here are some useful resources:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...