2012-04-14 38 views
2

我有两个输入文本字段。一个是输入文章的标题,另一个是文章的固定链接。我想要做的是永久性字段禁用,直到文本插入到标题字段中,并且当用户将焦点从标题字段中移出时,它会运行自定义正则表达式以用连字符替换空格,并将任何大写字母减小。使用模糊与文本字段

<input type="text" id="title" name"title" /> 
<input type="text" id="permalink" name="permalink" /> 
+4

你自己到底想到了什么? – sg3s 2012-04-14 13:14:30

+0

嗯,我正在寻找jQuery模糊函数的文档,我想知道如果这就是我应该使用的,除此之外,我期待看看是否有其他人使用它远程接近这一点,并没有看到任何东西线上。 – 2012-04-14 13:17:43

回答

6

这是一个与jQuery的真正的轻松......

var permalinkInput = $('#permalink'); 

$('#title').change(function() { 
    permalinkInput.prop('disabled', !$(this).val()); 
}).change().blur(function() { 
    $(this).val(function(i, value) { 
     return value.replace(/\s+/g, '-').toLowerCase(); 
    }); 
});​ 

jsFiddle

如果你没有的jQuery,但只需要支持符合标准的现代浏览器,这将会是......

var permalinkInput = document.querySelector('#permalink'), 
    titleInput = document.querySelector('#title'); 

permalinkInput.disabled = true; 

titleInput.addEventListener('change', function() { 
    permalinkInput.disabled = !titleInput.value; 
}, false); 

titleInput.addEventListener('blur', function() { 
    titleInput.value = titleInput.value.replace(/\s+/g, '-').toLowerCase(); 
});​ 

jsFiddle

如果你没有jQuery和必须支持我们的老IE的朋友,它会看起来像......

var permalinkInput = document.getElementById('permalink'), 
    titleInput = document.getElementById('title'); 

var addEvent = function(element, type, callback) { 
    if (element.addEventListener) { 
     element.addEventListener(type, callback, false); 
    } else if (element.attachEvent) { 
     element.attachEvent('on' + type, callback); 
    } else { 
     element['on' + type] = callback; 
    } 
} 

permalinkInput.disabled = true; 

addEvent(titleInput, 'change', function() { 
    permalinkInput.disabled = !titleInput.value; 
}); 

addEvent(titleInput, 'blur', function() { 
    titleInput.value = titleInput.value.replace(/\s+/g, '-').toLowerCase(); 
});​ 

jsFiddle

请注意,事件注册的旧回退是指定on*属性。这将覆盖此处分配的任何以前的属性。

如果您确实想为这些古老的浏览器注册多个事件,您可以修改属性分配以使用自定义处理程序,该处理程序会在需要时注册并触发多个事件。

+1

+1代码的效率,虽然因为永久链接只有一次使用它不需要是一个变量。 – sg3s 2012-04-14 13:22:23

+1

@ sg3s然而,它会被*选中*在每个'change'事件上不必要的。 – alex 2012-04-14 13:23:00

+0

正确。没有注意我猜:) – sg3s 2012-04-14 13:25:38