开发者

JavaScript Inline Events or Adding Events Afterwards

开发者 https://www.devze.com 2022-12-11 21:29 出处:网络
I have a question, which I can\'t seem to decide on my own so I\'ll ask here. The question is simple: whether to use inline JavaScript events or adding them afterwards? The theory in the background is

I have a question, which I can't seem to decide on my own so I'll ask here. The question is simple: whether to use inline JavaScript events or adding them afterwards? The theory in the background isn't that simple though:

I have a JS object that returns HTML. Whenever you create this object, the returned HTML will be used for another object's HTML. Therefore, adding events is not straight-forward. See:

secret.object = function() {
  this.init = function() {
    var html = '<div>and lots of other HTML content</div>';
    return html;
  };
}

This is a sample object that is created within this code:

for ( var i = 0; i < countObjects; i++) {
  var obj = arguments[0].content[i];
  generatedContent += spawnSecret(); /* The spawnSecret() is a method that initializes the object, and calls its init() method that returns the HTML.

}

and then later on I create a new object whose property "content" will be set to "generat开发者_运维知识库edContent". It needs to add the events within the secret object I have, nowhere else. And since my system is built like this, I see only two ways around this: use inline events or build HTML using method calling instead of returning.

Hopefully, this wasn't too hard to understand.


If you created the elements using document.createElement() (but didn't append them to the DOM) and kept a reference to them, then you could populate them with the text content and attach event handlers to them, without having to use inline events.

When you are ready to reveal your 'secret' you could then append them to the DOM, rather than dumping in a text string of HTML tags and content.


I cant see it making much of a difference - if you just render your events using onclick etc. JavaScript event handlers they will be evaluated as soon as you append your generated HTML to the document, rather than you having to call attachEvent() or whatever.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号