简体   繁体   English

在jQuery中将多个事件附加到单个函数

[英]Attaching multiple events to single function in jQuery

I'm looking for the opposite of that everyone's been looking for. 我正在寻找与每个人一直在寻找的相反的东西。 I have this anonymous jQuery function that I want to keep that way, but I want to attach multiple events handlers to it on different events (two events exactly). 我有这个匿名的jQuery函数,我希望保持这种方式,但我想在不同的事件(完全两个事件)上附加多个事件处理程序。

  1. When the textarea has text inside it changed ( keyup ) 当textarea里面的文本改变了( keyup
  2. When document is clicke ( click ). document是陈词滥调时( click )。

I know that grabbing the callback function and putting it in a function declaration, then using the function on both cases would do the job, but is there something around that wont require me to put the callback function in a normal function and just leave it as is? 我知道抓住回调函数并将其置于函数声明中,然后在两种情况下使用该函数都可以完成这项工作,但是有些东西不需要我将回调函数放在普通函数中而只是将其保留为是什么?

This is the code I currently have: 这是我目前的代码:

urls.keyup(function(){
    delay('remote', function(){
        if (urls.val().length >= char_start)
        {           
            var has_lbrs = /\r|\n/i.test(urls.val());

            if (has_lbrs)
            {
                urls_array = urls.val().split("\n");

                for (var i = 0; i < urls_array.length; i++)
                {
                    if (!validate_url(urls_array[i]))
                    {
                        urls_array.splice(i, 1);
                        continue;   
                    }
                }
            }
            else
            {
                if (!validate_url(urls.val()))
                {
                    display_alert('You might have inserted an invalid URL.', 'danger', 3000, 'top');
                    return; 
                }
            }

            final_send = (has_lbrs && urls_array.length > 0) ? urls_array : urls.val();

            if (!final_send)
            {
                display_alert('There went something wrong while uploading your images.', 'danger', 3000, 'top');
                return; 
            }

            var template = '<input type="text" class="remote-progress" value="0" />';

            $('.pre-upload').text('').append(template);
            $('.remote-progress').val(0).trigger('change').delay(2000);
            $('.remote-progress').knob({
                'min':0,
                'max': 100,
                'readOnly': true,
                'width': 128,
                'height': 128,
                'fgColor': '#ad3b3b',
                'bgColor': '#e2e2e2',
                'displayInput': false,
                'cursor': true,
                'dynamicDraw': true,
                'thickness': 0.3,
                'tickColorizeValues': true,
            });

            var tmr = self.setInterval(function(){myDelay()}, 50);        
            var m = 0;

            function myDelay(){
                m++;
                $('.remote-progress').val(m).trigger('change');

                if (m == 100) 
                {            
                    // window.clearInterval(tmr);
                    m = 0;
                }
            }

            $.ajax({
                type: 'POST',
                url: 'upload.php',

                data: {
                    upload_type: 'remote',
                    urls: JSON.stringify(final_send),
                    thumbnail_width: $('.options input[checked]').val(),
                    resize_width: $('.options .resize_width').val(),
                    album_id: $('#album_id').val(),
                    usid: $('#usid').val(),
                },

                success: function(data) {
                    // console.log(data); return;
                    var response = $.parseJSON(data);

                    if (response) 
                    {
                        $('.middle').hide();
                        $('.remote-area').hide();
                        window.clearInterval(tmr);
                    }

                    if ('error' in response)
                    {
                        //console.log(response.error);

                        if (!$('.top-alert').is(':visible'))
                        {
                            display_alert(response.error, 'danger', 3000, 'top');
                        }

                        return;
                    }

                    if (!target.is(':visible'))
                    {
                        target.show().addClass('inner');
                    }
                    else
                    {
                        target.addClass('inner');
                    }

                    for (var key in response) 
                    {
                        var image_url = response[key];

                        var thumb_uri = image_url.replace('/i/', '/t/');
                        var forum_uri = '[img]' + image_url + '[/img]';
                        var html_uri  = '&lt;a href=&quot;' + image_url + '&quot;&gt;' + image_url + '&lt;/a&gt;';

                        var view_url  = image_url.replace(/store\/i\/([A-Za-z0-9]+)(?=\.)/i, "image/$1");
                        view_url = strstr(view_url, '.', true);

                        // Append the upload box
                        target.append(upload_box(key));

                        // Hide knob
                        $('.knobber').hide();

                        // Put the image box
                        putImage($('.' + key), view_url, image_url, thumb_uri, forum_uri, html_uri);
                    }
                },
            }); 
        }

    }, 2000); // Delay
}); // Remote upload

How do I make this code run on document click as well? 如何在文档click运行此代码?

Thank you. 谢谢。

As you yourself has said in you question, the answer is to create an external named reference to the callback function and use it as the callback. 正如你自己在问题中所说,答案是创建一个对回调函数的外部命名引用,并将其用作回调。

Like 喜欢

jQuery(function () {
    function callback(e) {
        console.log('event2', e.type);
    }
    $('input').keyup(callback);
    $(document).click(callback)
})

But since you have asked for a different style have a look at, it essentially does the same as the above one 但是既然你要求一个不同的风格,它基本上与上面的相同

jQuery(function () {
    var callback;
    $('input').keyup(callback = function (e) {
        console.log('event', e.type);
    });
    $(document).click(callback)
})

Demo: Fiddle 演示: 小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM