我有两个输入文本字段。一个用于输入文章标题,一个用于输入文章的永久链接。我想要做的是禁用永久链接字段,直到将文本插入标题字段,并且当用户将焦点移出标题字段时,它会运行自定义正则表达式以用连字符替换空格并将所有大写字母小写。
<input type="text" id="title" name"title" />
<input type="text" id="permalink" name="permalink" />
最佳答案
使用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 friend ,它看起来就像......
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*
属性。这将覆盖之前分配的任何属性。
如果您确实想为这些古老的浏览器注册多个事件,则可以修改属性分配以使用自定义处理程序,该处理程序会注册并在需要时触发多个事件。
关于jquery - 对文本字段使用模糊,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10153912/