Putting icon instead of “ + ” or “ - ” in an accordian menu.js file

前端 未结 2 1623
南方客
南方客 2021-01-25 21:02

I am making an accordian menu.
I just found this link http://jsfiddle.net/zM5Vj/ , and it is almost similar to the accordian menu I have made.
In the code, where there i

相关标签:
2条回答
  • 2021-01-25 21:17

    $(this).text() allows you to specify plain text content for an element. To attach an image, use $(this).append($(<img src='plus.gif')).

    Also, instead of using $(this).text() == '-' to see if the menu has been expanded, attach a class to the <a> element.

    For example, we can use .addClass('expand') to indicate that the menu has expanded, and then .hasClass('expand') to check whether the menu has expanded, and finally '.removeClass('expand') to indicate that the menu is no longer expanded).

    Here's an example, using dummy images to illustrate:

    JSFiddle

    $(function(){
    
        //starter plus image
        var startPlus = $('<img>').attr('src','http://findicons.com/files/icons/1688/web_blog/48/add.png')
                                  .css({'height': '20px', 'width': '20px'});
    
        $('#accordion .fullChild>a.opener').addClass('box')
                                           .append(startPlus);
    
        $('#accordion .opener').click(function() {
    
            //images for click event handler
            var plusImg = $('<img>').attr('src','http://findicons.com/files/icons/1688/web_blog/48/add.png')
                                    .css({'height': '20px', 'width': '20px'});
            var minusImg = $('<img>').attr('src','http://findicons.com/files/icons/2083/go_green_web/64/subtract.png')
                                    .css({'height': '10px', 'width': '10px'});
    
            if($(this).hasClass('expand')) {
                $(this).empty()
                       .append(plusImg)
                       .removeClass('expand');
            } else {
                $(this).empty()
                       .append(minusImg)
                       .addClass('expand');
            }
        });
    });
    
    0 讨论(0)
  • 2021-01-25 21:18

    Thank You All for responding and helping me in solving it.
    @Simon Adcock, Your answer gave me a new way to think about the solution.
    However, i also found a 1 line solution to it.
    I just added this line to my .js file

     $(this).append($('<img src="../Images/imageplus.gif"/>'))
    

    So, answer finally it is :

    if (x == "block") {
            $(this).text('');
            $(this).append($('<img src="../Images/imageplus.gif"/>'))
            $(this).append(' ' + valueText);
        }
        else {
            $(this).text('');
            $(this).append($('<img src="../Images/imageminus.gif"/>'))
            $(this).append(' ' + valueText);
        }
    
    0 讨论(0)
提交回复
热议问题