我有两个输入文本字段.一个用于输入文章的标题,一个用于文章的固定链接.什么我想要做的是禁用,直到文本插入标题字段,当用户需要集中了冠军场的再运行一个自定义的正则表达式来替换连字符空格和小写字母的任何大写字母的永久场.
<input type="text" id="title" name"title" />
<input type="text" id="permalink" name="permalink" />
Run Code Online (Sandbox Code Playgroud)
使用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();
});
});?
Run Code Online (Sandbox Code Playgroud)
如果你没有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();
});?
Run Code Online (Sandbox Code Playgroud)
如果你没有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();
});?
Run Code Online (Sandbox Code Playgroud)
请注意,事件注册的旧回退是分配on*
属性.这将覆盖在那里分配的任何先前属性.
如果您真的想为这些古老的浏览器注册多个事件,则需要修改属性赋值以使用注册的自定义处理程序,然后在需要时触发多个事件.