-3

For my site I wrote a small piece of JavaScript that updates some elements in the browser when a button is clicked but this code seems to be redundant and inefficient. Is there any way to clean this up?

$(function () {
    $('#switch').click(function () {
        if ($('#header').text() == 'Sign In') {
            $('#header').text('Sign Up');
            $('#switch').text('Sign In');
            $('#submit').text('Sign Up');
            $('#submit').attr('form', 'sign_up');
        } else {
            $('#header').text('Sign In');
            $('#switch').text('Sign Up');
            $('#submit').text('Sign In');
            $('#submit').attr('form', 'sign_in');
        }
    });
});
4

1 回答 1

2

I can see a small improvement: don't query the jQuery objects each time you use them. Instead, store them in variables:

var $switch = $('#switch')
var $submit = $('#submit')
etc.

Then use those instead of querying for the same objects so many times.

$switch.click(function() {
        if ($header.text() == 'Sign In') {
            $header.text('Sign Up');
            $switch.text('Sign In');
            $submit.text('Sign Up');
            etc.
于 2013-03-30T13:07:03.200 回答