2011-07-29 102 views
1

我需要得到下面的JavaScript代碼以下任一環節的工作:我需要凝結這段JavaScript代碼

<a href="#" class="example1">http://example.com</a> 
<a href="#" class="test">Doesnt work now</a> 

被鏈接後顯示的代碼點:

<div style='display:none'> 
    <div id='example1' style='padding:10px; background:#fff;'> 
     <a href="http://example.com" target="_blank">Link</a> 
    </div> 
</div> 

的JavaScript代碼,我需要凝聚與任何類/ ID值,我給的工作:

<script> 
    $(document).ready(function(){ 
     $(".example1").colorbox({width:"50%", inline:true, href:"#example1"}); 
     $(".example2").colorbox({width:"50%", inline:true, href:"#example2"}); 
     $(".example3").colorbox({width:"50%", inline:true, href:"#example3"}); 
     $(".example4").colorbox({width:"50%", inline:true, href:"#example4"}); 
     $(".example5").colorbox({width:"50%", inline:true, href:"#example5"}); 
    }); 

+0

您試圖編寫的代碼在哪裏?這看起來像是一個請我做我的家庭作業的問題。 –

+0

您是否正在使用允許使用'.colorbox'的插件,或者是否有另一個未顯示的功能? –

+0

這是在當前網站上運行。我只需要能夠在鏈接類中添加任何值並將其匹配到div id。 '.colorbox'是一個插件 – josh

回答

5
$("[class^='example']").each(function() { 
    $(this).colorbox({width:"50%", 
         inline:true, 
         href:"#example" + $(this).attr("class").replace("example", "") 
    }); 
}); 

或更簡單:

$("[class^='example']").each(function() { 
    $(this).colorbox({width:"50%", 
         inline:true, 
         href:"#" + $(this).attr("class") 
    }); 
}); 
0
function myColorBox(myClass, myLink) { 
    return $("."+myClass).colorbox({width:"50%", inline:true, href:myLink}); 
}; 
0

目前還不清楚你問什麼,但它聽起來像你需要一個通用的方法來執行你的JavaScript代碼段列出的操作。嘗試是這樣的:

function doColorBox(sel, href) { 
    return $(sel).colorbox({width:'50%', inline:true, href:href}); 
} 
$(document).ready(function() { 
    doColorBox('.example1', '#example1'); 
    doColorBox('.test', 'http://test.com'); 
    doColorBox('#foo', '#foo'); 
}); 
0

一個簡單的for循環實際上可能比這些jQuery API的某些巧妙使用位更精簡。

$(document).ready(function(){ 
    for (var i = 1; i < 6; i++) 
    $(".example" + i).colorbox({width:"50%", inline: true, href:"#example" + i}); 
});