Is it not possible to separate javascript from HTML?

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:

$(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.

Thoughts?

+5
source share
8 answers

- , ID. , , , , rel:

<input type='text' id='title_33' class='title' rel='33' />

, , :

<input type='text' id='title_33' class='title' myval='33' />
+2

:

$(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);
    });
);
+7

, JavaScript HTML. /, , 10. .

jQuery live. 10 , 20 , 2 ( ).

, , . , , . , this.id.replace(/.*(\d+)$/,''). , , DOM .

, , , , . , , , mainupaliting id DOM - , ? , , .

+1

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 , :-(

+1

JavaScript. , , .

0

, .

$(".title").focus(function() {
   var thisid = this.id;
   updateCharsLeft(thisid.substring(thisid.indexOf("_") + 1));
});

, , .

0
source
$(document).ready(function(){
    var update = function(){ updateCharsLeft(this.id.split("_")[1]); };
    $("input.title")
        .focus(update)
        .keypress(update);
});
0
source

This is exactly what focuses on the unobtrusive Javascript technique .

0
source

All Articles