Skip to content Skip to sidebar Skip to footer

Jquery With Several Elements Issue

i got an anchor in the DOM and the following code replaces it with a fancy button. This works well but if i want more buttons it crashes. Can I do it without a for-loop? $(document

Solution 1:

Use the each method because you are fetching a collection of elements (even if its just one)

var button              =   $('a.makeabutton');
button.each(function () {
    var btn = $(this);
    var buttonContent       =   btn.text();
    var buttonStyle         =   btn.attr('class');
    var link                =   btn.attr('href');
    var linkTarget          =   btn.attr('target');
    var toSearchFor         =   'makeabutton';
    var toReplaceWith       =   'buttonize';
    var searchButtonStyle   =   buttonStyle.search(toSearchFor);
    ...
};

the each method loops through all the elements that were retrieved, and you can use the this keyword to refer to the current element in the loop

Solution 2:

var button              =   $('a.makeabutton');

This code returns a jQuery object which contains all the matching anchors. You need to loop through them using .each:

$(document).ready(buttonize);

functionbuttonize() {
    //alert(buttonAmount);//Lookup for the classesvar $buttons = $('a.makeabutton');
    $buttons.each(function() {
        var button = $(this);
        var buttonContent = button.text();
        var buttonStyle = button.attr('class');
        var link = button.attr('href');
        var linkTarget = button.attr('target');
        var toSearchFor = 'makeabutton';
        var toReplaceWith = 'buttonize';
        var searchButtonStyle = buttonStyle.search(toSearchFor);


        if (searchButtonStyle != -1) {

            newButtonStyle = buttonStyle.replace(toSearchFor, toReplaceWith);
            button.replaceWith('<span class="' 
                               + newButtonStyle 
                               + '"><span class="left"></span><span class="body">' 
                               + buttonContent 
                               + '</span><span class="right"></span></span>');

            $('.buttonize').click(function(e) {
                if (linkTarget == '_blank') {
                    window.open(link);
                } elsewindow.location = link;
            }); // end click
        } // end if

    }); // end each
}

Post a Comment for "Jquery With Several Elements Issue"