Jquery对话 - 可在多图像上重复使用

时间:2013-09-27 12:23:32

标签: javascript jquery html

我正在使用Jquery UI对话框在我的页面上弹出图像。

目前,对于每张图片,我使用以下内容:

<script type="text/javascript">
        $("#myImageInfo").dialog({
            autoOpen: false,
            draggable: false,
            position: "center",
            width: "300px",
            modal: true,
            title: "Image Title",
            buttons: {
                "Close": function () {
                    $(this).dialog("close");
                }
            }
        });

        $("#MyImageLink")

          .click(function () {
              $("#MyImageInfo").dialog("open");
          });

    </script>

我的HTML,

<a id="MyImageLink" href="#">
        <img src="blahblahblah.jpg"></a>


    <div id="MyImage" title="Basic modal dialog">
         <p><strong>Title Yah</strong></p>
        <p>
            <strong>Phone</strong>: ****<br />
            <strong>Email</strong>:<a href="mailto:"></a>
            </a>
    </div>

我的问题是我有大约10张图片设置相同,每张图片都有其他ID,我怎么能更有效地使用这个脚本所以我只需要包含一次?感谢。

2 个答案:

答案 0 :(得分:1)

ID必须是唯一的。但您可以将同一个类名应用于多个元素。

您可以为所有这些元素指定相同的类名。然后使用

$(".className").dialog({
            autoOpen: false,
            draggable: false,
            position: "center",
            width: "300px",
            modal: true,
            title: "Image Title",
            buttons: {
                "Close": function () {
                    $(this).dialog("close");
                }
            }
        });

答案 1 :(得分:0)

好的你不能把同一个id多个elems放在同一个页面上,id必须是唯一的postfix一些计数器值,如MyImageLink1, MyImageLink2, MyImageLink3或更好的选项是将id更改为class这样:

<a class="MyImageLink" href="#"><img src="blahblahblah.jpg"></a>

<div class="MyImage" title="Basic modal dialog">
    .......
</div>

脚本:

<script type="text/javascript">
   function dialg(e){
        e.preventDefault();
        $(".myImageInfo").dialog({
            autoOpen: false,
            draggable: false,
            position: "center",
            width: "300px",
            modal: true,
            title: "Image Title",
            buttons: {
                "Close": function () {
                    $(this).dialog("close");
                }
            }
        });
   }

    $(function(){
        $(".MyImageLink").on('click', dialg);
    });

    </script>