这应该可行:
function name_to_url(name) {
name = name.toLowerCase(); // lowercase
name = name.replace(/^\s+|\s+$/g, ''); // remove leading and trailing whitespaces
name = name.replace(/\s+/g, '-'); // convert (continuous) whitespaces to one -
name = name.replace(/[^a-z-]/g, ''); // remove everything that is not [a-z] or -
return name;
}
然后
$('input[name=article]').blur(function() {
$('input[name=url]').val(name_to_url($(this).val())); // set value
});
这会在每次文章字段失去焦点时设置 url 字段中的值。
它保留名称中已经存在的-。因此,如果您也想删除它们,则必须将name_to_url() 的倒数第二行和倒数第三行更改为:
name = name.replace(/[^a-z ]/g, ''); // remove everything that is not [a-z] or whitespace
name = name.replace(/\s+/g, '-'); // convert (continuous) whitespaces to one -
参考:.blur()、.val()、.toLowerCase()、.replace()
更新:
我会创建一个新函数,比如说update_URL():
function update_URL() {
var value = name_to_url($('input[name=article]').val()) + '-' + $('input[name=year]').val();
$('input[name=url]').val(value)
}
然后你可以在任何事件上调用这个函数,例如在keyup():
$('input[name=article]').keyup(function() {
update_URL();
});