Creating multiple instances of dialog box

谁说我不能喝 提交于 2019-12-08 05:59:45

问题


I'm new to jQuery and java and I'm really trying to get my head round creating multiple instances of a dialog box. I'm using this in the head:

 <script src="external/jquery/jquery.js"></script>
 <script src="jquery-ui.js"></script>

If I just have 1 button and and dialog box it works. But when I add another it stops working. I'm sure it will be quite easy to fix I'm just struggling.

        <h2>subjects</h2>

        <button id="opener">maths</button>

        <div id="dialog" title="Dialog Title">maths is an important subject.</div> <br> 

      <button id="opener">english</button>

        <div id="dialog" title="Dialog Title">this is also very important</div> <br>

       <script>

        $( "#dialog" ).dialog({ autoOpen: false });
        $( "#opener" ).click(function() {
        $( "#dialog" ).dialog( "open" );
                                         });
        </script>

回答1:


http://jsfiddle.net/y7952dmf/

  1. ID must be unique and therefore used the class in order to work with several other elements of the same time
  2. To link button and the dialog for example, use data-id for button and id for dialog with same value

HTML:

<h2>subjects</h2>

<button class="opener" data-id="#dialog1">maths</button>
<div class="dialog" id="dialog1" title="Dialog Title">maths is an important subject.</div>
<br>

<button class="opener" data-id="#dialog2">english</button>
<div class="dialog" id="dialog2" title="Dialog Title">this is also very important</div>
<br>

JQ:

//create all the dialogue
$(".dialog").dialog({
    autoOpen: false
});

//opens the appropriate dialog
$(".opener").click(function () {
    //takes the ID of appropriate dialogue
    var id = $(this).data('id');
   //open dialogue
    $(id).dialog("open");
});



回答2:


IDs are used to tell it what object you are working with. You need to give them separate names to have it know what to work with.

  <h2>subjects</h2>

    <button id="openerMath">maths</button>

    <div id="dialogMath" title="Dialog Title">maths is an important subject.</div> <br> 

  <button id="openerEnglish">english</button>

    <div id="dialogEnglish" title="Dialog Title">this is also very important</div> <br>

   <script>

    $( "#dialogMath" ).dialog({ autoOpen: false });
    $( "#openerMath" ).click(function() {
    $( "#dialogMath" ).dialog( "open" );
                                     });
    $( "#dialogEnglish" ).dialog({ autoOpen: false });
    $( "#openerEnglish" ).click(function() {
    $( "#dialogEnglish" ).dialog( "open" );
                                     });
    </script>

This should be what you are looking for.



来源:https://stackoverflow.com/questions/27238592/creating-multiple-instances-of-dialog-box

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!