开发者

Is there a way to share a jQuery context?

I'm trying to use jQuery Button to build a button bar for each item on my page; however following the examples I get poor performance when the number of items goes over 100. I've added context to my calls which helped a little but it bugs me that I'm revisting the same context for each button built.

Below is an example of the code used to add a two button button bar to each item in my page. The context is the same, but it gets iterated over for each button in the button bar. Is the开发者_如何学JAVAre a way to iterate over this context once and apply the code to setup each button?

function initLater()
{
    $(function () {

        $('input.ItemSelect', $('#container fieldset div.controls div.controlsToolbar')).button({
            text: false,
            icons: {
                primary: 'ui-icon-check'
            }
        });
        $('a.btnPrint', $('#container fieldset div.controls div.controlsToolbar')).button({
            text: false,
            icons: {
                primary: 'ui-icon-print'
            }
        });
    });
}


You can store and re-use the reference using .find(), like this:

function initLater()
{
    $(function () {
        var ctx = $('#container fieldset div.controls div.controlsToolbar');
        ctx.find('input.ItemSelect').button({
            text: false,
            icons: {
                primary: 'ui-icon-check'
            }
        });
        ctx.find('a.btnPrint').button({
            text: false,
            icons: {
                primary: 'ui-icon-print'
            }
        });
    });
}

A $(selector, context) call is really just a context.find(selector) internally anyway, you can see how it's handled here :)

Alternatively, you can chain it using .end(), like this:

$('#container fieldset div.controls div.controlsToolbar')
  .find('input.ItemSelect').button({
    text: false,
    icons: { primary: 'ui-icon-check' }
}).end().find('a.btnPrint').button({
    text: false,
    icons: { primary: 'ui-icon-print' }
});


I don't see why not. $('#container fieldset div.controls div.controlsToolbar') is just an instance of the jQuery object, so it can be stored:

function initLater()
{
    $(function () {
         var cntxt = $('#container fieldset div.controls div.controlsToolbar');
        $('input.ItemSelect', cntext).button({
            text: false,
            icons: {
                primary: 'ui-icon-check'
            }
        });
        $('a.btnPrint', cntext).button({
            text: false,
            icons: {
                primary: 'ui-icon-print'
            }
        });
    });
}


Yes.

var toolbar = $('#container fieldset div.controls div.controlsToolbar');

toolbar.find('input.ItemSelect').button(...);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜