【问题标题】:jquery/javascript prepend text into input fieldjquery/javascript 在输入字段中添加文本
【发布时间】:2012-11-09 07:21:00
【问题描述】:

我有一个使用 html5 占位符的输入框:

<input type="text" name="website" class="url" required placeholder="enter website">

使用 jQuery 或直接 javascript,我想在用户键入的数据前添加一个字符串。如果该字段包含的数据多于预设的字符串变量(例如:http://example.com),则该字段满足我的要求。如果它只包含原始字符串('http://'),则清除输入值并显示占位符。

以下代码适用于我。

var input = $("#processor .url");
var prefix = 'http://';

input.focus(function() {
    if (input.val().indexOf(prefix) == -1) {
        input.val(prefix + input.val());
    }
}).blur(function() {
    if (input.val() == prefix) {
        input.val('');
    }
});

有没有更好的方法来写这个以提高性能等等...,这是我真正的问题吗?

【问题讨论】:

  • 您想在用户输入前添加“http://”吗?

标签: javascript jquery placeholder


【解决方案1】:

这比实际看起来要容易。 我根据@Tahir Yasin 的评论做了一个演示。

css:

.grey { color:#aaa; }

html:

<input type="text" />

jQuery:

var inputval = "";
$(document).ready(function() {
    // Define your default value to show on input
    $("input[type='text']").val("Enter your link here...");
    // Add grey color or optionally blur effect
    $("input[type='text']").addClass('grey');
    // Save your default value
    inputval = $("input[type='text']").val();
    $("input[type='text']").focusin(function() {
    // if textbox is empty or got the default value
    if ($(this).val() == "" || $(this).val() == inputval) {
        // Clear the box
        $(this).val("http://"); // Your text here..
        // Remove grey color
        $(this).removeClass('grey'); }
    }).focusout(function() {
        // if textbox is empty or just contains your value
        if ($(this).val() == "" || $(this).val() == "http://" ) {
            // Put your Default value back
            $(this).val(inputval);
            // Add grey color
            $(this).addClass('grey'); }
    });
});

小提琴:http://jsfiddle.net/BerkerYuceer/TgZ8L/

我只是喜欢在动作的每一步都使用 jQuery。但是您可以看到我的代码的性能不如您的代码,因此您已经在使用最高效的方式。

这是基于您的代码的演示: http://jsfiddle.net/BerkerYuceer/qbLyD/

您可以自己看到差异几乎相同,但显然您的代码更快。

【讨论】:

    猜你喜欢
    • 2012-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-02
    • 1970-01-01
    • 2015-12-21
    • 1970-01-01
    • 2018-04-04
    相关资源
    最近更新 更多