2010-09-22 56 views
0

起初,抱歉我的英語。 我的問題是:我有PHP生成的動態股利,與ID和圖像源..如果用戶點擊動態股利其交換IMG源。 我的腳本工作,但它交換所有div圖像,但沒有選擇div img源碼。 問題在哪裏?我如何交換點擊div img源碼?有人能幫助我嗎?jquery和用戶城市

我的腳本:

<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> 

和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="table" border="0" 
    usemap="#tableMap" class="hoverswap" 
    style='cursor:pointer; z-index:-300; width:118px; height:51px;'/> 
</div> 
+0

And div:

Nation 2010-09-22 08:33:34

回答

0

使用

$(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"); 
     }); 
    }); 

還可以編輯CSS的div.area_map

div.area_map{ 
position:relative; 
} 

這會讓你的z-index的工作相對於area_map

+0

你能給我你的電子郵件嗎?我想發送完整的源代碼給你。 – Nation 2010-09-22 09:02:08

+0

只需在http://jsfiddle.net/中添加代碼,點擊保存並在這裏更新網址 – 2010-09-22 09:10:34

+0

我不能把php,只是html,java和css – Nation 2010-09-22 09:25:07

0

要澄清JapanPro和zrytane,$('img.hoverswap')給出的答案,找出所有匹配的文檔中,無論你從所謂的範圍吧。

$('img.hoverswap', this)將範圍限制爲this而不是默認值document

$(this).find('img.hoverswap')this設置了一個jQuery包裝,然後在其中進行搜索。

兩者效果都很好,但您必須親自對其進行基準測試,以確定是否存在速度差異。 (直觀上,不應該有)

但是,由於您反覆創建和放棄jQuery對象,因此腳本效率低下。以下是我想它的代碼:

<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> 

這樣的話,你只創建了img.hoverswap查詢一次包裝,然後發送多個命令。您還會注意到我使用了.css()的映射表單,由於Javascript對象文字的限制,它使用camelCase而不是虛線名稱。

+0

Tnx,它的工作。但是Z指數有問題。Swaped D5。png在grass.png下? – Nation 2010-09-22 09:13:53

+0

在DOM Inspector(Chrome內置或Firefox擴展)中將其拉起來,並查看兩個圖像的「計算樣式」列表中的z-index值。這會告訴你問題在哪裏。 – ssokolow 2010-09-22 09:30:45

+0

Okey,tnx。我會嘗試。 – Nation 2010-09-22 09:34:48