简体   繁体   中英

Image swap with a javascript onclick dropdown menu

So I've got this code that has an image and when you click it a dropdown menu appears. Pretty simple. The code works fine but I'm trying to incorporate an image swap on click and I'm having difficulty. Here's the HTML and the JS (there's some CSS too, but I'll leave that out):

HTML:

<div id="header">
  <dl class="dropdown">
    <dt><a href="#"><img src="images/cogwheel_btn.png"/></a></dt>
    <dd>
    <ul>
        <li><a href="#">Favorites</a></li>
        <li><a href="#">History</a></li>
    </ul>
    </dd>
  </dl>
</div>

JS:

$(document).ready(function() {
$(".dropdown dt a").click(function() {
    $(".dropdown dd ul").toggle();
});     
$(".dropdown dd ul li a").click(function() {
    var text = $(this).html();
    $(".dropdown dt a span").html(text);
    $(".dropdown dd ul").hide();
    $("#result").html("Selected value is: " + getSelectedValue("sample"));
});       
function getSelectedValue(id) {
    return $("#" + id).find("dt a span.value").html();
}
$(document).bind('click', function(e) {
    var $clicked = $(e.target);
    if (! $clicked.parents().hasClass("dropdown"))
    $(".dropdown dd ul").hide();
});
});

I've tried adding lines like ("dt").empty(); and then ("dt").html("new_image") but it causes the dropdown functionality to stop working. Anyone any ideas?

I have created code at JSFiddle. Just check if this is how you would like it to behave:

http://jsfiddle.net/3L3At/2/

I think you'll be wanting to update the src attribute of your image -

You can find the image in the dropdown like this:

$('.dropdown dt img')

Then update the src attribute

$('.dropdown dt img').attr('src', '/newimage.jpg');

I suspect you'll want this in the click function like so:

$(".dropdown dt a").click(function() {
    $(".dropdown dd ul").toggle();
    $('.dropdown dt img').attr('src', '/newimage.jpg');
});  

Note that if you want it to toggle on/off, you could check for the visibility of the ul element with the .is(':visible') check. Or better still, replace the image with a div, and use a background image changed with toggleClass() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM