2010-02-26 68 views
1

第一屬性,請參閱this post on Doctype匹配相對與jQuery

我一直在試圖讓一個答案,但都沒有成功。第一張海報提供的腳本效果很好,但是,我需要這樣做自動發生,適用於所有匹配Rel's組。

任何援助將不勝感激。

編輯: 對於那些你無法按照上面的鏈接,這裏是腳本:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head><title>match rel</title> 
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> 
<script type="text/javascript"> 
$(function() { 
    $("input[type='button']").click(function(){ 
    $(".photo img").show().css('background','transparent'); //restore visibility 
    matchImg($("#relval").val()); 
    }); 
}); 

function matchImg(relVal){ 
    var sel = ".photo img[rel='" + relVal + "']"; 
    if ($(sel).length > 0) { //check matching rel 
     $(sel + ":gt(0)").hide(); //hide all except first 
     $(sel + ":first").css('background','red'); //set background to first 
    } 
} 
</script> 
<style type="text/css"> 
.photo img { 
    padding: 5px; 
    float: left; 
} 
</style> 
</head> 
<body> 
<div class="photo"> 
<img rel="dt" src="http://doctype.com/images/logo-small.png" alt="1" /> 
<img rel="dt" src="http://doctype.com/images/logo-small.png" alt="2" /> 
<img rel="dt" src="http://doctype.com/images/logo-small.png" alt="3" /> 
<img rel="so" src="http://sstatic.net/so/img/logo.png" alt="4" /> 
<img rel="so" src="http://sstatic.net/so/img/logo.png" alt="5" /> 
</div> 
<p style="clear: both;"> 
Enter 'dt' or 'so' <input type="text" value="dt" id="relval" /> 
<input type="button" value="match" /> 
</p> 
</body> 
</html> 

基本上,我服用的照片網格佈局和修改它們。有些照片是相關的,有些則不是。相關的將具有匹配的Rel屬性。我想jquery識別一組相關圖像(使用相同的rel),隱藏除第一個圖像以外的所有圖像,並將背景圖像應用於第一張照片的容器(尚未最終確定,但它可能是一個div或者李)。

這個腳本已經這樣做了。

但是,我需要的腳本來自動做到這一點,所有的配套相對羣體,有沒有我在rel屬性進入。

+1

想象一下你提供的URL是死的。現在,我該如何幫助你?請詢問實際問題。 – rochal 2010-02-26 15:24:50

+2

'rel'屬性只允許使用'a'和'link'元素。你應該使用類來代替。 – Gumbo 2010-02-26 15:36:14

+0

如果你能拿出執行與類相同功能的腳本,是我的客人:) – Batfan 2010-02-26 15:42:45

回答

3

好劇本會做的第一件事情是找出所有的「相對」值。

$(function() { 
var allRels = {}; 
$('img[rel]').each(function() { 
    allRels[$(this).attr('rel')] = true; 
}); 

然後你可以通過隱藏所有,但第一(或不管它是什麼,你想做的事):

$.each(allRels, function(rel) { 
    $('img[rel=' + rel + ']').each(function(i) { 
    if (i == 0) { 
     // $(this) is the first image with this particular "rel" value 
    } 
    else { 
     // $(this) is another image in the group, but not the first 
    } 
    }); 
}); 

});

我沒有測試過這一點,但也許你的想法。

+0

良好的開端,但不幸的是,將是數以百計的版本屬性。我無法將它們全部定義。基本上,我使用jquery修改由另一個軟件生成的HTML頁面。 – Batfan 2010-02-26 15:34:49

+0

那麼你不是*在這裏定義*他們,你*找到*他們。代碼將查看頁面中的內容,並有效地創建所有唯一值的「設置」數據結構。我編輯了這篇文章,修復了可以做到這一點的代碼塊。 – Pointy 2010-02-27 14:34:57