2016-02-18 6 views
0

Я сделал один помощник для открытия нового всплывающего окна при щелчке, и у меня возникла проблема с установкой значений по умолчанию внутри объекта. Мне нужно вычислить положение для TOP и LEFT для всплывающего окна, чтобы центрировать новое всплывающее окно. Вот полный код:jQuery: Как получить значение из этого «объекта»?

/* 
    $(element).onPopup(options); - Open Popup window 
    -Ths function open new popup window on your browser 

    EXAMPLE: 
    ---------------------------------------------- 
    <a href="http://google.com">Google</a> 

    $("a#link").onPopup({ 
     name  : "Popup Window", 
     width  : 800, 
     height  : 600 
    }); 

    OPTIONS: 
    ---------------------------------------------- 
    attr   // attribute where is located link 
    name   // name of popup window 
    width   // max width 
    height   // max height 
    left   // position left (px) 
    top    // position top (px) 
    resizable  // resizable 1 or 0 
    location  // display location 1 or 0 
    fullscreen  // open in full screen 1 or 0 
    scrollbars  // display scroll bars 1 or 0 
    titlebar  // display title bar 1 or 0 
    toolbar   // display tool bar  1 or 0 
    directories  // display directories 1 or 0 
*/ 
$.fn.onPopup=function(options){ 
    var s = { 
      attr  : "href", 
      name  : "Popup Window", 
      width  : 700, 
      height  : 600, 
      left  : ($(window).width()/2)-(this.width/2), 
      top   : ($(window).height()/2)-(this.height/2), 
      resizable : 0, 
      location : 0, 
      fullscreen : 0, 
      scrollbars : 1, 
      titlebar : 0, 
      toolbar  : 0, 
      directories : 0 
     }, 
     $element = this; 

    s = $.extend(s,options); 

    $element.on("click",function(e) { 
     e.stopPropagation(); e.preventDefault(); 
     window.open(
      $(this).attr(s.attr), s.name, "width="+s.width+", height="+s.height+", directories="+s.directories+", toolbar="+s.toolbar+", titlebar="+s.titlebar+", scrollbars="+s.scrollbars+", fullscreen="+s.fullscreen+", location="+s.location+", resizable="+s.resizable+", top="+s.top+", left="+s.left 
     ); 
    }); 
}; 

А вот где моя проблема:

var s = { 
      /*...*/ 

       width  : 700, 
       height  : 600, 
       left  : ($(window).width()/2)-(this.width/2), 
       top   : ($(window).height()/2)-(this.height/2), 

      /*...*/ 

      }, 

Как пройти ширина/высота на другой объект для работы?

+0

Вы спрашиваете, как ссылаться на 's.width' из одного и того же объекта? Так что 'this.width === 700'? – Ivan

+2

вы не можете получить доступ к значению другого ключа из одного и того же литерала объекта – Alnitak

ответ

2

Один из способов создать объект первым затем добавить дополнительные свойства, которые ссылаются на другие свойства в объекте

var s = { 
     attr  : "href", 
     name  : "Popup Window", 
     width  : 700, 
     height  : 600, 
     left  : null, //calculated if not user provided 
     top   : null //calculated if not user provided 
     .... 
    }; 

// update user settings 
s = $.extend(s,options); 

// calculate based on actual values 
if(s.left === null){ 
    s.left = ($(window).width()/2)-(s.width/2); 
} 
if(s.top === null){ 
    s.top = ($(window).height()/2)-(s.height/2); 
} 

отметить Также вы должны return this.each(.. и запустить свой бизнес там, чтобы у вас есть отдельные случаи, когда селектор содержит более один элемент, а также сделать плагин с другими методами jQuery

+0

, который не позволяет пользователю указывать их собственное предпочтительное значение вместо – Alnitak

+0

@ Алнитак уверен, что это так ... '$ .extend' позаботится об этом – charlietfl

+0

нет, это не так: вы переписываете любое значение, которое было передано в 'options.left' или' options.top' в последних двух строках – Alnitak

0

В соответствии с вашим API в комментариях кода вы хотите, чтобы вызывающий абонент мог указать свои собственные позиции left и top.

Поэтому вам необходимо проверить, были ли какие-либо значения предоставлены вообще, и только затем рассчитать позицию по умолчанию на основе заданной ширины и высоты.

var s = { 
    ... // defaults, *not including* "left" and "top" 
}; 

// override the defaults with the user-supplied options 
// NB: no need to re-assign to `s` - `$.extend` overwrites 
//  the contents of the first parameter 
$.extend(s, options); 

// then calculate `left` and `top` if they weren't supplied 
if (s.left === undefined) { 
    s.left = ($(window).width() - s.width)/2; 
} 
if (s.top === undefined) { 
    s.top = ($(window).height() - s.height)/2; 
}