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
300 views
in Technique[技术] by (71.8m points)

javascript attaching events

I've seen that you can attach events like this

<button type="button" id="myButton" onclick="myFunction()">

can you do the same without the "onclick=", like:

document.getElementById('myButton'). //and here attach the event on click to myFunction

I'm trying to keep JavaScript and HTML separate.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

It's similar to the onclick approach, and in fact uses the same event-handler, but is removed from the HTML:

document.getElementById('myButton').onclick = function(){
    // do stuff
    myFunction();
}

If you don't have an id on the element you could also use:

var inputs = document.getElementsByTagName('input');

for (var i=0, len=inputs.length; i<len; i++){
    if (inputs[i].type == 'text'){
        // assuming you want to affect text-inputs in this case
        inputs[i].onclick = function(){
            // do stuff. In here 'this' refers to inputs[i] element
            myFunction();
        };
    }
}

An alternative approach, using Array.prototype.forEach(), with an array of elements created using Array.prototype.slice() and document.querySelectorAll():

[].forEach.call(document.querySelector('input[type="text"]', yourFunctionName);

This will execute the yourFunctionName() function for each <input /> element, of type="text", returned by document.querySelectorAll() passing that <input /> element into the function as this.

You could also use addEventListener() in this case:

document.getElementById('myButton').addEventListener('click', myFunction, false);

And also in this situation, using document.querySelector() (as opposed to document.querySelectorAll()), which returns the first element that matches the passed-in selector, using CSS notation:

// gets the element with an 'id' of 'myButton', binding the 'click' event-handler:
document.querySelector('#myButton').addEventListener('click', myFunction, false);

Or:

// gets the first of the <input> elements, binding the 'click' event-handler:
document.querySelector('input').addEventListener('click', myFunction, false);

References:


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

...