我正在尝试构建一个使用正则表达式替换字符的小插件。如果我在文本框中删除超过 1 个字符并模糊,它只会删除该字符。它不会“镜像”文本框中的值,并且看起来具有当前值。
(function ($) {
$.fn.friendlyUrl = function (destinationID) {
return this.blur(function () {
var title = $(this).val();
var url = title
.replace(/[åä]/g, "a")
.replace(/[ÅÄ]/g, "A")
.replace(/ö/g, "o")
.replace(/Ö/g, "O")
.replace(/[^a-zA-Z0-9]/g, "-")
.replace(/^-+/, "")
.replace(/-+$/, "")
.replace(/-+/g, "-")
.toLowerCase();
$(destinationID).val(url);
});
};
})(jQuery);
我用以下方式调用它:
$("#PageName").friendlyUrl("#Url");
这里可能出了什么问题?
最佳答案
我做了一些修改。
假设输入的是url:
<input type="text" id="PageName"/>
插件代码:
(function ($) {
$.fn.friendlyUrl = function () {
return this.blur(function () {
var title = $(this).val();
var url = title
.replace(/[åä]/g, "a")
.replace(/[ÅÄ]/g, "A")
.replace(/ö/g, "o")
.replace(/Ö/g, "O")
.replace(/[^a-zA-Z0-9]/g, "-")
.replace(/^-+/g, "")
.replace(/-+$/g, "")
.replace(/-+/g, "-")
.toLowerCase();
$(this).val(url);
});
};
})(jQuery);
和调用:
$(document).ready(function(){
$("#PageName").friendlyUrl();
});
你真的不需要在这里传递 id
关于javascript - 对于 jquery 插件,replace 一次仅替换 1 个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18874386/