-1

只是想要一些关于如何更好地编写此代码的意见,它工作正常,我只是想学习如何更好地编写 jQuery,所以我想要一些聪明人的意见。谢谢!

它通过查找“PO”的变体来检查送货地址字段以查看它是否包含邮政信箱地址,然后在输入后显示警告消息,如果它确实包含它。

http://jsfiddle.net/ferne97/6RnxG/

(function ($) {
    var $shipAddress = $('input[name="user_data[s_address]"]'),
        message = '<div class="message hidden"><p>We <strong>don\'t ship to PO Boxes</strong>. Sorry for the inconvenience.</p></div>';

    $shipAddress.after(message);

    $shipAddress.keyup(function () {
        var $value = $(this).val();

        if ($value === 'po' || $value === 'p.o' || $value === 'PO' || $value === 'P.O') {
            $shipAddress.siblings('.message').removeClass('hidden');
        } else if ($value === '') {
            $shipAddress.siblings('.message').addClass('hidden');
        }
    });

}(jQuery));
4

1 回答 1

1

It's pretty good code. I see you are adding/removing classes to hide/show elements. Instead of using classes to handle the visibility of elements, you could do .hide() and .show(). This will add/remove inline style display: none;

So, instead of

$shipAddress.siblings('.message').removeClass('hidden');
$shipAddress.siblings('.message').addClass('hidden');

You can do simply:

$shipAddress.siblings('.message').show();
$shipAddress.siblings('.message').hide();

So you don't need to write extra css classes. But thats only a minor improvement. Maybe that's only a matter of opinion, but i would prefer hide and show function.

See: http://jsfiddle.net/6RnxG/2/

于 2013-02-07T21:26:01.263 回答