jQuery Dialog,简化代码

时间:2013-03-13 13:06:29

标签: jquery jquery-ui-dialog

我正在使用jQuery Dialog,如下所示: -

    <a href="#" id="faq-1"><li><span class="black">- I paid for a journey on credit card and at a later date I got further charges. Why?</span></li></a>

    <div id="faq-1a" class="faq-a" title="I paid for a journey on credit card and at a later date I got further charges. Why?">
        <p>When a booking is made via credit card we take the payment for the journey quoted. If for any reason the journey was amendments i.e.  Waiting time or an extra drop off, these charges are separately billed therefore shown as a separate transaction on your statement.</p>
    </div>

    <a href="#" id="faq-2"><li><span class="black">- How do I get a receipt for a journey I made using my credit card?</span></li></a>

    <div id="faq-2a" class="faq-a" title="How do I get a receipt for a journey I made using my credit card?">
        <p>If you are a registered user please use your online booking management via our website <a href="index.php">www.one2onecars.com</a>. you will have access to all your journeys with the option to print out receipts for each journey or as a summary statement. If you are not registered, you can email <a href="mailto:creditcardreceipts@one2onecars.com">creditcardreceipts@one2onecars.com</a> for your receipts.</p>
    </div>

JQUERY

   $(function() {

        $('.faq-a').dialog({
          modal: true,
          resizable: false,
          draggable: false,
          width: '585',
          autoOpen: false,
          position: [370,455],
        });
    });

});

    $("#faq-1").bind('click', function(){

        $("#faq-1a").dialog('open')

    });

    $("#faq-2").bind('click', function(){

        $("#faq-2a").dialog('open')

    });

我需要为10个不同的对话框执行此操作,因此#faq-x范围从#faq-1#faq-10

我确信会有更简单的方法来写这个,这样我就不必再重复了:

$("#faq-3").bind('click', function(){

    $("#faq-3a").dialog('open')

});

对于我创建的每个对话框,我都无法弄清楚我是如何做到的,所以任何帮助都会非常感激!

3 个答案:

答案 0 :(得分:0)

检查你是否可以在jquery中简单地编写以下for循环。

for (var i = 1; i <= 10; i ++) {
     $("#faq-" + i).bind("click", function() {
         $("#faq-" + i + "a").dialog("open")
     });
}

答案 1 :(得分:0)

为什么不创建Class而不是唯一ID?

为#faq-1,#faq-2,........,#faq-10指定所有相同的类,例如,faqClass

$(".faqClass").bind('click', function(){
    $("#" + $(this).attr('id') + "a").dialog('open');
});

答案 2 :(得分:0)

一种方法是将jquery绑定添加到类中,并向锚点添加其他数据属性:

在这里小提琴:http://jsfiddle.net/qV578/1/

HTML:

<a href="#" data-dialog="one" class="dialog-link">Link</a>
<div id="one" class="dialog">Dialog fired by Link</div>

使用Javascript:

$('.dialog').dialog({
      modal: true,
      resizable: false,
      draggable: false,
      width: '585',
      autoOpen: false,
      position: [370,455]
    });

$('.dialog-link').bind('click',function(e) {
    e.preventDefault();
    var target_dialog = $(this).attr('data-dialog');
    $('#'+target_dialog).dialog('open');
});