Действительно ли невозможно разделить JavaScript от HTML?

Строго это должно соответствовать

[A-Za-z][-A-Za-z0-9_:.]*

, Но jQuery, кажется, имеет проблемы с двоеточиями, таким образом, могло бы быть лучше избежать их.

5
задан Rich Seller 21 July 2009 в 16:45
поделиться

8 ответов

Мне приходилось делать что-то подобное раньше и тоже не было » Я доволен анализом значения атрибута ID. Лучшее, что я могу предложить, это использовать другой атрибут для нужного вам значения, например атрибут rel :

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

Или, в зависимости от того, насколько вы религиозны в отношении проверки, просто используйте настраиваемый атрибут:

<input type='text' id='title_33' class='title' myval='33' />
2
ответ дан 13 December 2019 в 19:33
поделиться

If you really don’t want to pass this.Id then you could add a custom attribute to the input tag...

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

You then set the event handlers like this...

$(document).ready(function()
{
    $(".title").focus(function() {
        updateCharsLeft(this.idSuffix);
    });
    $(".title").keypress(function() {
        updateCharsLeft(this.idSuffix);
    });
);

I personally like custom attributes. They provide a way to give Html tags custom metadata and keep it all in the markup. Html validators don’t like them though :-(

1
ответ дан 13 December 2019 в 19: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);
    });
);
7
ответ дан 13 December 2019 в 19:33
поделиться

I definitely think you should separate your JavaScript and HTML. It will be easier to find/maintain, and you can edit one place rather than 10. Don't repeat yourself.

I would look into using jQuery's live functionality. If you have 10 text input's, your adding 20 event handlers this way as opposed to 2 (one for EVERY focus handler on the page and one for EVERY keypress handler on the page).

Also re your comment to karim, I don't see why you would be duplicating yourself. It should be trivial to pass the id or transform it with a regular expression if necessary as long as your consistent in your naming convention For example, this.id.replace(/.*(\d+)$/,''). However, it would probably even be better to pass the direct DOM element reference instead, and work with that in your function.

Lastly, you seem to think that some aspect of this will suck. Maybe I'm missing the point, but can you clarify what's so difficult about mainupaliting the id or the DOM reference or whatever else that you need to do? Maybe post a longer code sample of what you're doing next.

1
ответ дан 13 December 2019 в 19:33
поделиться

Я бы попытался управлять всеми событиями из одного блока JavaScript. Если вы можете ссылаться на элементы на странице, это должно быть возможно.

0
ответ дан 13 December 2019 в 19:33
поделиться

Вы всегда можете использовать строковые функции, чтобы проанализировать значение и передать его, например

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

Я не уверен, каковы были бы последствия для производительности, если бы вам пришлось сделать это для Хотя много элементов.

0
ответ дан 13 December 2019 в 19:33
поделиться
$(document).ready(function(){
    var update = function(){ updateCharsLeft(this.id.split("_")[1]); };
    $("input.title")
        .focus(update)
        .keypress(update);
});
0
ответ дан 13 December 2019 в 19:33
поделиться

This is exactly what Unobtrusive Javascript technique focuses on.

0
ответ дан 13 December 2019 в 19:33
поделиться
Другие вопросы по тегам:

Похожие вопросы: