To be specific, I am talking about avoiding this type of code:
<input type='text' id='title_33' class='title' onfocus='updateCharsLeft(33);' onkeypress='updateCharsLeft(33);' />
Here I would like to put the event descriptors onfocusand onkeypressseparately, ie in the .js file. Like this:
onfocus
onkeypress
$(document).ready(function() { $(".title").focus(updateCharsLeft); $(".title").keypress(updateCharsLeft); );
However, the problem here is that the text field identifier needs to be passed to the function updateCharsLeft(). It would suck to extract the identifier from the text field identifier in this function, so it would actually be easier to just put event handlers in the HTML code.
updateCharsLeft()
Thoughts?
- , ID. , , , , rel:
rel
<input type='text' id='title_33' class='title' rel='33' />
, , :
<input type='text' id='title_33' class='title' myval='33' />
:
$(document).ready(function() { $(".title").focus(function() { updateCharsLeft(this.id); }); $(".title").keypress(function() { updateCharsLeft(this.id); }); );
$(document).ready(function() { $(".title .another .someother .andAnother").focus(function() { updateCharsLeft(this.id); }).keypress(function() { updateCharsLeft(this.id); }); );
, JavaScript HTML. /, , 10. .
jQuery live. 10 , 20 , 2 ( ).
, , . , , . , this.id.replace(/.*(\d+)$/,''). , , DOM .
this.id.replace(/.*(\d+)$/,'')
, , , , . , , , mainupaliting id DOM - , ? , , .
this.Id, ...
this.Id
<input type='text' id='title_33' idSuffix='33' class='title'/>
$(document).ready(function() { $(".title").focus(function() { updateCharsLeft(this.idSuffix); }); $(".title").keypress(function() { updateCharsLeft(this.idSuffix); }); );
. Html- . Html , :-(
JavaScript. , , .
, .
$(".title").focus(function() { var thisid = this.id; updateCharsLeft(thisid.substring(thisid.indexOf("_") + 1)); });
, , .
$(document).ready(function(){ var update = function(){ updateCharsLeft(this.id.split("_")[1]); }; $("input.title") .focus(update) .keypress(update); });
This is exactly what focuses on the unobtrusive Javascript technique .