Putting icon instead of “ + ” or “ - ” in an accor

2019-03-04 00:19发布

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 is

if($(this).text() == "-")  
{
  $(this).text("+");
  }
  else {
  $('#accordion .opener').text("+");
  $(this).text("-");
   }
 });

If insted of "+" and "-", i want to put icons "~/Image/iconplus.gif" and "~/Image/iconminus.gif". How do i do so?
I have tried

<img src="..."/>

But still it is of no use.
Please can anyone help?
Thanks in advance.

2条回答
混吃等死
2楼-- · 2019-03-04 00:56

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);
    }
查看更多
做个烂人
3楼-- · 2019-03-04 01:12

$(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');
        }
    });
});
查看更多
登录 后发表回答