2011-07-29 57 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}); 
});