0

I have the following script which works great however I think this can be simplify, right? also, I'd like it to trigger only once.

Example, user inputs "My Title". Script executes and user sees "my-title" in slug field. If user replaces title value by "My Crazy Title", I'd like the slug to remain "my-title". How?

$('#article_title').change(function() {
  str = $('#article_title').val();
  formatted = str.replace(/\s+/g, '-').toLowerCase();
  $('#article_slug').val(formatted);
});

See code example http://jsfiddle.net/TSrYu/

4

3 回答 3

1
var changed = false;
$('#article_title').change(function () {
    // do some other stuff
    if (!changed) {
        str = $(this).val();
        formatted = str.replace(/\s+/g, '-').toLowerCase();
        $('#article_slug').val(formatted);
    }
    changed = true;
});

http://jsfiddle.net/mohammadAdil/TSrYu/1/

于 2013-04-23T21:52:41.373 回答
1

你可以这样简化:

  1. 切换到使用.one()来注册您的事件处理程序,以便它只触发一次。
  2. 删除中间变量并一次处理所有字符串

编码:

$('#article_title').one('change', function() {
    $('#article_slug').val($(this).val().replace(/\s+/g, '-').toLowerCase());
});

工作演示:http: //jsfiddle.net/jfriend00/XGjWA/

于 2013-04-23T22:09:32.110 回答
0

您可以进行两个小的改进:

  • 没有通过正确声明变量来使变量全局化。
  • 不再为元素查询 DOM,因为它已经可以通过访问this

为了确保它只发生一次,您可以取消绑定事件(片段中的最后一行

$('#article_title').change(function() {
  var str = $(this).val();
  var formatted = str.replace(/\s+/g, '-').toLowerCase();
  $('#article_slug').val(formatted);
  $(this).unbind("change");
});
于 2013-04-23T21:54:41.573 回答