开发者

jquery and user city

at first, sorry about my english. My question is: I have php generated dynamic div, with id and image source.. If user click on dynamic div its swap img source. My script works, but its swaps all div images, but not selected div img source. Where is problem? how I can swap clicked div img source? Can someone, help me please?

My script:

<script> ( function($) { 
  $(document).ready( function() { 
    $("div.area_map").click( function () { 
      $('div[id^=grass]').each(function(div) { 
        $('img.hoverswap').css("width","229"); 
        $('img.hoverswap').css("height","124");
        $('img.hoverswap').attr("src","default/citymap/D5.png"); 
        $('img.hoverswap').css("z-index", "9999") 
       } ); 
     }); 
   } ) ( jQuery ); 
</script>

And div:

<div class="area_map" id="grass
  <?php echo $k+$st_x/2; ?>" 
  style='cursor:pointer; width:118px; height:51px; position:absolute; 
  left:<?php echo $st_x; ?>px; 
  top:<?php echo $st_y; ?>px;'>
  <img src="default/citymap/Zale2.png" name="tab开发者_开发技巧le" border="0" 
    usemap="#tableMap" class="hoverswap" 
    style='cursor:pointer; z-index:-300; width:118px; height:51px;'/> 
</div>


use

$(document).ready( function() { 
    $("div.area_map").click( function () { 
                $('img.hoverswap')
                .css(
                {
                "width":"229",
                "height":"124",
                "position":"absolute",//to make z-index work
                "z-index", "9999"
                })
                .attr("src","default/citymap/D5.png");
       }); 
   });

also edit css for div.area_map

div.area_map{
 position:relative;
}

this will make your z-index work relative to area_map


To clarify the answers given by JapanPro and zrytane, $('img.hoverswap') finds all matches in the document, regardless of what scope you call it from.

$('img.hoverswap', this) restricts the scope to this rather than the default of document.

$(this).find('img.hoverswap') sets up a jQuery wrapper for this and then searches within it.

Both work equally well but you'd have to benchmark them yourself to see if there's a speed difference. (Intuitively, there shouldn't be)

However, your script is inefficient since you're repeatedly creating and discarding jQuery objects. Here's how I'd code it:

<script>
 (function($) { 
  $(document).ready( function() { 
    $("div.area_map").click( function () { 
        $('img.hoverswap', this).css({
            width: "229",
            height: "124",
            zIndex: "9999"
        }).attr("src","default/citymap/D5.png"); 
    }); 
  }); 
 }) ( jQuery ); 
</script>

That way, you're only creating the wrapper for the img.hoverswap query once and then sending multiple commands. You'll also notice I've used the map form of .css() which, due to restrictions on the Javascript object literal, uses camelCase rather than dashed-names.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜