开发者

improving custom jquery code tips

Ok, so here is a code for a very very very basic jQuery lightbox, the problem is that I need to write new line of code for every differently clicked elements. My question is how can bind this lightbox to every class or id with something like rel="qpLighbox" attached to it and use the href tag to fetch the needed file via AJAX. so here is the current code

$(".user_settings").click(function() {

         $("#qpbox-content").show();
         $("#qpbox-overlay").show();
         开发者_Python百科$("#qpbox-loader").html("<img src='images/4.gif' />");

         var xhr = $.ajax({
         type: "GET",
         url: "ajax.php",
         data: "ajax=1&ajax_f=user[settings]",
         success: function(html){
            $("#qpbox-utm").html(html);
            $("#qpbox-loader").html("");
         },
         error: function (XMLHttpRequest, textStatus, errorThrown) {$("#qpbox-loader").html(errorThrown);}
         });

         });


You may want to modify this so that the data sent to the URL can change (e.g. by adding data-xx attributes to links, where xx is whatever the name for the data is.)

// Binds the lightbox to all links whose rel attribute is qpLightbox
$("a[rel='qpLightbox']").click(function(e) {
    e.preventDefault();

    // Use the link's href attribute as the src for the lightbox content.
    var url = $(this).attr("href");

    $("#qpbox-content").show();
    $("#qpbox-overlay").show();
    $("#qpbox-loader").html("<img src='images/4.gif' />");

    $.ajax({
        type: "GET",
        url: url,
        data: "ajax=1&ajax_f=user[settings]",
        success: function(html) {
            $("#qpbox-utm").html(html);
            $("#qpbox-loader").html("");
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            $("#qpbox-loader").html(errorThrown);
        }
    });

});


$(this).attr('href') inside of your click event gives you the href value. as of selector can you just make all element that you need to attach to this click event with the same class?

if you need to filter by rel you can add in your selector something like

$('.yourClass[rel=\'yourRel\']')
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜