2011-01-14 67 views
0
$("a[rel='view-show-info']").click(function() { 
    $(this).parent().next('.show-info').slideToggle(70); 

    var img = $("img", this).attr("src"); 
    if(img == "<?=base_url();?>assets/images/plus.png") // or check the end of the path or similar 
    $("img", this).attr("src", "/images/minus.png"); 
    else 
    $("img", this).attr("src", "/images/plus.png"); 

    return false; 
}); 

<a href="#" rel="view-show-info" class="view-more"> 
    <img src="/images/plus.png" alt="expand selection"> 
</a> 

根據用戶點擊的內容顯示加號或減號圖像。根據鏈接狀態附加標題以鏈接(a href)標記

我想爲鏈接添加一個標題,如果圖片顯示的是minus.png圖片,請將title設置爲title =「合約選擇」,如果顯示的是plus.png圖片,則將其設置爲title = 「擴大選擇」

因此鏈接將是這樣的:

minus.png:

<a href="#" rel="view-show-info" class="view-more" title="contract selection"> 
    <img src="/images/minus.png" alt="contract selection"> 
</a> 

plus.png

<a href="#" rel="view-show-info" class="view-more" title="expand selection"> 
    <img src="/images/plus.png" alt="expand selection"> 
</a> 

我想我必須使用append函數,但是盡我所知,任何幫助表示讚賞。

回答

2

您可以使用.closest向上遍歷樹並找到錨(這樣你就可以改變它的標題屬性):

var src = '/images/plus.png'; 
var title = 'expand selection'; 
if(img == "<?=base_url();?>assets/images/plus.png") 
{ 
    src = '/images/minus.png'; 
    title = 'collapse selection'; 
} 
$("img", this) // grab your image (per normal) 
    .attr({'src':src,'alt':title}) // change the source 
    .closest('a') // go up the three to find the anchor 
    .attr('title',title) // change the anchor's title 

編輯哎呀,你要爲錨。
EDIT2改變了一下代碼,使其更加簡化。現在也改變img alt屬性。 (仍在IE上工作)

+0

似乎可以在除IE7以外的任何應用程序中工作。 – Brad 2011-01-14 16:47:09

0
if(img == "<?=base_url();?>assets/images/plus.png"){ 
    $("img", this).attr("src", "/images/minus.png").parent().attr('title', 'contract selection'); 
} else { 
    $("img", this).attr("src", "/images/plus.png").parent().attr('title', 'expand selection'); 
} 
+0

在IE7中不起作用 – Brad 2011-01-14 16:52:20