开发者

Way to shorten jquerycode

I have several modal popup windows which all use the same settings. One of these requires the following code.

var $modal = $('#modal')
  .attr('id', 'modal')
  .css({zIndex: 3000});

$('#modal-trigger').click(function(evt) {
  evt.preventDefault(), $('#modal').css("visibility","visible");

  $(this).overlay({
    effect: 'fade',
    glossy: true,
    opacity: 0.8,
    closeOnClick: true,
    onShow: function() {
      $('body').append($modal);
    },
    onHide: function() {
      $modal.remove();
    },
  })
});

So making a second one means changing the modal to some开发者_如何学JAVAthing else in the following places:

var $modal = $('#modal')

.attr('id', 'modal')

$('#modal-trigger').click(function(evt) {

$('body').append($modal);

$modal.remove();

Is there a way to shorten this, so I do not have to keep adding the full code to achieve this effect?


Write a jQuery plugin. It's easy. http://docs.jquery.com/Plugins/Authoring

That said, it looks like you'd probably be reimplementing something like jQuery blockUI.


BTW, there is no reason to select an element by ID and immediately set its ID attribute as this line of code does:

$('#modal').attr('id', 'modal')


I would propose:

  • caching elements (using variables you created),
  • using function within callback (passing "context" and the element to be influenced when clicking the trigger,
  • not assigning something that has been assigned (by #modal you are selecting something that already has id="modal",

It would look like that (it has not been tested however):

var $modal1 = $('#modal1').css({zIndex: 3000});
var $modal2 = $('#modal2').css({zIndex: 3000});

var doStuff = function(context, element){
  element.css("visibility","visible");
  context.overlay({
    effect: 'fade',
    glossy: true,
    opacity: 0.8,
    closeOnClick: true,
    onShow: function() {
      $('body').append(element);
    },
    onHide: function() {
      element.remove();
    },
  })
}

$('#modal1-trigger').click(function(evt){
    evt.preventDefault();
    doStuff($(this), $modal1);
});

$('#modal2-trigger').click(function(evt){
    evt.preventDefault();
    doStuff($(this), $modal2);
});

Please let me know if you find any errors there.


Make it a function? I think this should work:

function doStuff(id)
{
    var $modal = $('#' + id)
  .attr('id', id)
  .css({zIndex: 3000});

$('#' + id + '-trigger').click(function(evt) {
  evt.preventDefault(), $('#' + id).css("visibility","visible");

  $(this).overlay({
    effect: 'fade',
    glossy: true,
    opacity: 0.8,
    closeOnClick: true,
    onShow: function() {
      $('body').append($modal);
    },
    onHide: function() {
      $modal.remove();
    },
  })
});
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜