2012-01-05 69 views
1

我有这个代码适用于输入测试类型onClick="this.value+='http://'",但我想修改它,以便它只添加http://第一次用户单击输入。添加文本一次输入点击

任何想法?谢谢。

+2

不确定你为什么使用这个容易出错的代码。为了满足你的愿望,在这里你去:'onClick =“this.value + ='http://'; this.onclick ='';'' – 2012-01-05 11:27:43

+0

谢谢,回答,我会接受。 – jacktheripper 2012-01-05 11:29:51

回答

3

的回答你的问题是显而易见的(稍微修改,添加前缀http://文本):

onClick="this.value = 'http://' + this.value; this.onclick = '';" 

然而,这种方法很容易出错,和丑陋。您可能希望强制文本的前缀为http://。如果用户使用键导航到输入字段(例如选项卡),则代码将不起作用。

改进的方法是:

onfocus="if (this.value.substring(0,6)!=='http://') this.value = 'http://' + this.value;" 

不过,根据您的具体应用,其它的方法更适合。

2

您可以在全局设置一个计数器变量并检查它是否等于1 add http://否则 不会添加。

1

试试这个:

<input type="text" onClick=" this.value.indexOf('http://') != 0 ? this.value = 'http://' + this.value : this.value; " /> 
+0

这个答案不正确。最接近的解决方案是:'onClick =“if(this.value.indexOf('http://')!= 0)this.value ='http://'this.value;”'。 – 2012-01-05 11:46:40

+1

感谢罗布修复了我的代码示例。 – 2012-01-05 13:22:02