简体   繁体   中英

Alternative to inline scripting in JavaScript

I am aware that in-line scripting should be avoided by keeping html/css and javascript separated.

How is it possible to do such a thing in the following code? //consider above in the code the function alertMe() declared

<img src="LittleBrain.png"  id="littlebrain" onClick="alertMe();">

How would it be possible not using in line code?

Thanks in advance.

With addEventListener() :

var img = document.getElementById('littlebrain');
img.addEventListener('click', function(event){
  alertMe();
});
document.getElementById('littlebrain').onclick = function() { alertMe(); }

甚至更短:

document.getElementById('littlebrain').onclick = alertMe;

In a JavaScript code file, you can find the img element by its id , and then you can set its onclick handler. For example, using jQuery:

$("#littlebrain").click(function () {
  // ...handler code here...
});

In your case, the handler is a named function, called alertMe :

$("#littlebrain").click(alertMe);

It depends on the browsers you have to support, but if you're lucky and only get to worry about modern browsers, you can use .addEventListener()

var thing = document.getElementById('thing');

thing.addEventListener('click', function(e) {
  // do something here!
}, false);

If you're not so lucky, then you'll have to come up with a cross browser solution..

var thing = document.getElementById('thing');

addEvent(thing, 'click', function() {
  // do something
});

function addEvent(elem, event, callback) {
  if (elem.addEventListener) {
    elem.addEventListener(event, callback, false);
  } else if (elem.attachEvent) { // IE7 and earlier
    elem.attachEvent('on' + event, function() {
      callback.apply(elem, arguments);
    });
  } else {
    elem['on' + event] = callback;
  }
}

Or, if you use a library like jQuery, you can easily normalize the whole process

$('#thing').on('click', function() {
  // do something...
});
var el = document.getElementById('littlebrain');
el.addEventListener('click', alertMe, false);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM