2014-09-10 93 views
0

我有一個動態的圖像縮略圖列表。每次選擇圖像時,我想取消選擇當前選擇的圖像並選擇新點擊的圖像。在HTML看起來象下面這樣:突出顯示並在jquery中選擇的未加亮項目

<ul class="imgList"> 
    <li> 
     <div id="item1" class="imgStyle" order="{#}" imgId="{imgId}"> 
      <img src="{imgPath}"/> 
     </div> 
    </li> 
    <li> 
     <div id="item2" class="imgStyle" order="{#}" imgId="{imgId}"> 
      <img src="{imgPath}"/> 
     </div> 
    </li> 
    <li> 
     <div id="itemn" class="imgStyle" order="{#}" imgId="{imgId}"> 
      <img src="{imgPath}"/> 
     </div> 
    </li> 
</ul> 

我使用jQuery綁定的click事件的項目是這樣的:

$(".imgStyle img").bind("click", function() { 
    $(item1).css("border", "5px solid grey"); 
} 

我很容易能夠選擇/高亮顯示單擊的項目。但是,如何取消選擇之前突出顯示的項目(div)? 謝謝!

回答

2

你應該使用CSS類:

.selected { border: 5px solid gray;} 

$('.imgList').on('click','img', function() { 
    $(this).parents('.imgList').find('.selected').removeClass('selected').end().end().addClass('selected'); 
}); 
+0

我認爲我更快。但是,既然你提供了相關的css風格,我會給你的答案=) – 2014-09-10 18:43:01

+0

謝謝!正是我在找什麼.. – kriver 2014-09-10 19:02:56

-1

繼方法,你已經這樣做:

$(".imgStyle img").bind("click", function() { 
    $(".imgStyle img").removeAttr("style"); 
    $(item1).css("border", "5px solid grey"); 
} 

由於jQuery的.css()方法添加屬性元素的內嵌style屬性,刪除everyother IMG的這種風格應該是足夠

但是

你最好使用一個類來定義一個選定的元素,如:

.selected { 
    border: 5px solid gray; 
} 

然後:

$(".imgStyle img").bind("click", function() { 
    $(".selected").removeClass("selected"); 
    $(this).addClass("selected"); 
} 
+0

如果他不想刪除現有的樣式元素會怎麼樣? – 2014-09-10 18:40:28

+0

@JamesHill,我從'HTML看起來像下面:'這不是這種情況... – LcSalazar 2014-09-10 18:45:09

1

我很少直接操作CSS樣式,而是添加一個類,當它不再使用時,我只是刪除課程。

例如

$(".imgStyle img").bind("click", function() { 
    $(".imgStyle").removeClass("highlight"); 
    $(item1).addClass("highlight"); 
} 
+0

感謝更簡單的解決方案! – kriver 2014-09-10 19:03:40

相關問題