开发者

Using regex to change sub element image from off to on and back

开发者 https://www.devze.com 2023-01-09 10:47 出处:网络
In an eff开发者_JS百科ort to keep code down I was hoping to use regular expressions with jQuery to switch the on and off states inside a hover for an image.

In an eff开发者_JS百科ort to keep code down I was hoping to use regular expressions with jQuery to switch the on and off states inside a hover for an image.

jQuery:

$(function(){
  $("ul.dropdown li").hover(function(){
    $(this).addClass("hover");
    $('ul:first',this).css('visibility', 'visible');

  }, function(){
    $(this).removeClass("hover");
    $('ul:first',this).css('visibility', 'hidden');
  });
});

html:

<ul class="dropdown">
  <li><a href=""><img src="images/nav_first_off.png" /></a>
    <ul class="sub_menu sub1"><li>
      <div class="topnav_dropdown_left"><a href=""><img src="images/topnav_dropdown_first.jpg" /></a></div>
    </li></ul>
  </li>
  <li><a href=""><img src="images/nav_second_off.png" /></a>
    <ul class="sub_menu sub2"><li>
      <div class="topnav_dropdown_left"><a href=""><img src="images/topnav_dropdown_second.jpg" /></a></div>
    </li></ul>
  </li>
  <li><a href=""><img src="images/nav_third_off.png" /></a>
    <ul class="sub_menu sub3"><li>
      <div class="topnav_dropdown_left"><a href=""><img src="images/topnav_dropdown_third.jpg" /></a></div>
    </li></ul>
  </li>
</ul>

So with using the hover function above changing the subsequent nav_first_off.png, nav_second_off.png with the li hover and using the regex to cut the _off.png and switch to _on.png.

Any help would be appreciated, and thanks for even looking.


You can pass a function into .attr() to change the src attribute, like this:

$(function(){
  $("ul.dropdown li").hover(function(){
    $(this).addClass("hover");});
    $('ul:first',this).css('visibility', 'visible');
    $('a img', this).attr('src', function(i, src) { 
      return src.replace('_off','_on'); 
    });
 }, function(){
    $(this).removeClass("hover");
    $('ul:first',this).css('visibility', 'hidden');
    $('a img', this).attr('src', function(i, src) { 
      return src.replace('_on','_off'); 
    });
  });
});

In the function, the src parameter in function(i, src) is the old src value, so we're just doing a .replace() on that, you can pass it a more complicated regex if needed as well.

0

精彩评论

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