结合document.load + blur

时间:2013-01-11 01:12:39

标签: javascript jquery

我有以下javascript来确定版权是否格式正确:

    var copyright = $('#copyright')
    var copyright_text = copyright[0].value
    if (copyright_text.length > 0) {
        var containsYear = /\d{4}/.test(copyright_text);

        if (containsYear == false) {
            copyright.css({
               'background-color': 'rgba(230, 89, 78, 0.07)',
            });
            copyright.parent().append(
               '<div class="explanatory caution">CAUTION: Make sure this copyright contains a year.</div>'
            );

        };
    };

如何将同样的逻辑应用于.blur()以及上面的正常页面加载,而不复制并粘贴上面的所有代码?

2 个答案:

答案 0 :(得分:1)

添加后,您可以使用.trigger触发回调:

$(document).ready(function() {
    $('#copyright').blur(function() {
        var copyright = $('#copyright')
        var copyright_text = copyright[0].value
        if (copyright_text.length > 0) {
            var containsYear = /\d{4}/.test(copyright_text);

            if (containsYear == false) {
                copyright.css({
                   'background-color': 'rgba(230, 89, 78, 0.07)',
                });
                copyright.parent().append(
                   '<div class="explanatory caution">CAUTION: Make sure this copyright contains a year.</div>'
                );

            };
        };
    }).trigger('blur');
});

答案 1 :(得分:0)

将您拥有的代码放入函数中。当您感兴趣的事件发生时调用它:

$(document).load(function(){
    formatCopyright();

    $(<the-selector>).blur(function({
        formatCopyright();
    });

    function formatCopyright({
        // the code from your question goes here
    });
});