开发者

Faster Javascript text replace

开发者 https://www.devze.com 2022-12-25 19:25 出处:网络
Given the following javascript (jquery) $(\"#username\").keyup(function () { selected.username = $(\"#username\").val();

Given the following javascript (jquery)

        $("#username").keyup(function () {
            selected.username = $("#username").val();

            var url = selected.protocol +
                (selected.prepend == true ? selected.username : selected.url) + "/" +
                (selected.prepend == true ? selected.url : selected.username);

            $("#identifier").val(url);
        });

This code basically reads a textbox (username), and when it is typed into, it reconstructs the url that is being displayed in another textbox (identifier).

This works fine - there are no problems with its functionality. However it feels 'slow' and 'sluggish'. Is there a cleaner/faster way to accomplish this ta开发者_如何学JAVAsk?

Here is the HTML as requested.

<fieldset class="identifier delta">
    <form action="/authenticate/openid" method="post" target="_top" >
        <input type="text" class="openid" id="identifier" name="identifier" readonly="readonly" />
        <input type='text' id='username' name='username' class="left" style='display: none;'/>
        <input type="submit" value="Login" style="height: 32px; padding-top: 1px; margin-right: 0px;" class="login right" />
    </form>
</fieldset>

The identifier textbox just has a value set based on the hyperlink anchor of a button.


Cache your jquery objects...

var username = $('#username'),
    identifier = $('#identifier');

username.keyup(function () {
    selected.username = username.val();

    var url = selected.protocol +
        (selected.prepend == true ? selected.username : selected.url) + "/" +
        (selected.prepend == true ? selected.url : selected.username);

    identifier.val(url);
});

you are currently searching the dom twice on each key stroke.


Other than saving from one less IF I don't see any optimization possible.

var url = selected.protocol + (selected.prepend == true ? selected.username + '/' + selected.url : selected.url + '/' + selected.username);


Yeah as the others have shown... the only optimization I can see is moving the objects outside the function:

var url = selected.protocol;
var iden = $("#identifier");
$("#username").keyup(function() {
 selected.username = $(this).val();
 iden.val( url + (selected.prepend == true ? selected.username + '/' + selected.url : selected.url + '/' + selected.username) );
})
0

精彩评论

暂无评论...
验证码 换一张
取 消