I would like to call a funct开发者_开发知识库ion when any of my <span>
elements is clicked.
document.body.span.onClick = function(){
// do something
}
Can someone show me the right way to do this? Thanks in advance!
var spans = document.getElementsByTagName("span");
for (var i = 0; i < spans.length; i++) {
spans[i].onClick = function() {
// do something
}
}
You should really use jQuery for something like this.
window.onload = function() {
var allSpans = document.getElementsByTagName("span");
for (var i = 0; i < allSpans.length; i++) {
allSpans[i].onclick = spanClickHandler;
}
}
function spanClickHandler(e) {
// do something
}
Try this:
var spans = document.getElementsByTagName("SPAN");
var spansCount = spans.length;
for(var i=0; i<spansCount; i++){
spans[i].onClick = function(){
//YOUR_CODE
}
}
P.S: Why not take a look at jQuery JS Framework and see if you can start using it.
Use jQuery and write.
function myFunction(){
// Do your thing.
}
$(window).load(function () {
$('span').click(myFunction);
});
Yes, you just need to download the jQuery js file and include it at the top of the page to make this work. I highly recommend learning jQuery as it can simplify a lot of things. You can mix jQuery style code and "regular" JS too, without problem.
精彩评论