javascript - 当用户通过jquery在文本框中输入时,如何自动添加字符串 "http://'

标签 javascript jquery html

我想自动在文本框的值前面加上 http://

例如,cateno.no 应变为 http://cateno.no,但 http://google.com 应保留一样的。

这是 HTML:

<input id="urlBanner" type ="text" style ="width:450px;" maxlenght="100" />

最佳答案

您可以绑定(bind)到 change 输入的事件并评估值:

$(document).ready(function () {
    $("#urlBanner").change(function() {
        if (!/^http:\/\//.test(this.value)) {
            this.value = "http://" + this.value;
        }
    });
});

示例: http://jsfiddle.net/andrewwhitaker/gnHLz/

或者,如果您不喜欢正则表达式,您可以使用 indexOf :

$(document).ready(function () {
    $("#urlBanner").change(function() {
        if (this.value.indexOf("http://") !== 0) {
            this.value = "http://" + this.value;
        }
    });
});

示例: http://jsfiddle.net/andrewwhitaker/fYRUW/

关于javascript - 当用户通过jquery在文本框中输入时,如何自动添加字符串 "http://',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9073566/

相关文章:

javascript - Electron 检测全局滚动事件Mac

javascript - 将属性名称隐式传递给对象方法的正确方法是什么?

javascript - 谷歌地图多色折线

javascript - 如何使用 javascript 进行相对路径重定向?

javascript - 变换 rotate() 不适用于 Animate.css

html - 如果文本没有包含在按钮中,那么在一些文本之后应该有 "..."

javascript - 避免无限循环

html - CSS 显示调整大小和裁剪的图像

javascript - jQuery 在单击 anchor 元素时处理 href

java - 如何在java中生成签名并在jQuery(Cloudinary)中使用它?