Создание динамических кнопок «предыдущий следующий» в диалоговом окне jquery UI - PullRequest
1 голос
/ 19 октября 2010

Я искал все это на этом сайте и в Интернете

Можно ли динамически создавать предыдущие и следующие кнопки в диалоговом окне jquery?

У меня есть список ссылок, и я хотел бы нажать на ссылку и открыть диалоговое окно. В этом диалоговом окне была бы предыдущая и следующая кнопка, которая при нажатии закрывала бы текущее диалоговое окно и открывала предыдущий или следующий элемент списка в другом диалоговом окне и т. Д.

Что-то вроде этого

HTML

<ul id="dialoglist">
  <li>
    <a href="list1.html">
  </li>
  <li>
    <a href="list2.html">
  </li>
  <li>
    <a href="list3.html">
  </li>
  <li>
    <a href="list4.html">
  </li>
</ul>

JQuery

$("ul#dialoglist a").click(function(){
    var link = $(this).attr('href') + " #content";
    var box = $('<div></div>').load(link).dialog({
        buttons: {
            "prev": function() {
                 $(this).dialog('close');
                 //open previous dialog
             },
             "next": function() {
                 $(this).dialog('close');
                 //open next dialog
             }
        }
    });
    $(box).dialog('open');
    return false;
});

Спасибо

Ответы [ 3 ]

4 голосов
/ 19 октября 2010

Что-то вроде этого должно работать:

$("ul#dialoglist a").click(function(){
    var a = $(this);
    var link = a.attr('href') + " #content";

    // move button creation here so we can dynamically build 
    // the button hash:

    var aParent = a.parent();
    var buttons = {};
    var prevLi = aParent.prev();
    var nextLi = aParent.next();

    if(prev.length > 0){
      buttons.prev = function(){
        // not sure if this is in the corret scope here - you may need to select by id
        $(this).dialog('close');
        $('a', prevLi).click();
      };
    }

    if(next.length > 0){
      buttons.next = function(){
        / not sure if this is in the corret scope here - you may need to select by id
        $(this).dialog('close');
        $('a', nextLi).click();
      };
    }

    var box = $('<div></div>').load(link).dialog({
        'buttons': buttons
    });
    $(box).dialog('open');
    return false;
});

Поскольку вы просто запускаете событие щелчка по предыдущим / следующим ссылкам, вам не нужно беспокоиться о ручном открытии диалогов.

Однако... зачем открывать новые диалоги, а не использовать api виджетов диалогов для прямой установки содержимого?

0 голосов
/ 02 сентября 2013

JS

    $(function() {  
        /* construct prev/next button */
        $(".dialog div.dialogs").each(function (i) {
            var totalSize = $(".dialog div.dialogs").size() - 1;           
            if (i != 0) {
                prev = i - 1;
                $(this).append("<div class='prev_button'><a href='#tabs' class='prev-tab mover' rel='" + prev + "'>Previous</a></div>");
            }

             if (i != totalSize) {
                next = i + 1;
                $(this).append("<div class='next_button'><a href='#tabs' class='next-tab mover' rel='" + next + "'>Next</a></div>");
            }
        });

        /* next button click */
        $('.next-tab').click(function () {
              var nextDialog= $(this).parent().parent().data("id") + 1;  
              var currentDialog = $(this).parent().parent(); currentDialog.dialog("close");
              $("#dialog"+ nextDialog).dialog();
        });

        /* previous button click */
        $('.prev-tab').click(function () {
              var prevDialog = $(this).parent().parent().data("id") - 1;  
              var currentDialog = $(this).parent().parent(); currentDialog.dialog("close");
              $("#dialog"+ prevDialog).dialog();
        });

        /* intial dialog(first) */
        $( "#dialog1" ).dialog();   
  });

HTML

<div class="dialog" style="display:none">
    <div id="dialog1" class="dialogs" data-id="1" title="dialog1">
      <p>Dialog content1</p>
    </div>
    <div id="dialog2" class="dialogs" data-id="2" title="dialog2">
      <p>Dialog content2</p>
    </div>
    <div id="dialog3" class="dialogs" data-id="3" title="dialog3">
      <p>Dialog content3</p>
    </div>
    <div id="dialog4" class="dialogs" data-id="4" title="dialog4">
      <p>Dialog content4</p>
    </div> 
</div>

PLUGGINS

<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
0 голосов
/ 01 августа 2013

Я новичок в Jquery, у меня есть немного опыта, но немного, но решение prodigitalson выглядит великолепно, мне просто кажется, что, поскольку вы получаете событие click, вам не нужнопредотвратить ссылку по умолчанию?В противном случае, он просто попытается следовать указаниям, указанным в привязке, верно?

Извините, что опубликовал это как ответ, но моей репутации недостаточно, чтобы оставить комментарий ...

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...