![](/img/trans.png)
[英]How can I combine 60 similar jquery functions into a single function?
[英]jQuery: use a single function instead of repeated functions for similar operations
目前,我正在使用fancybox顯示這樣的iframe:
$('#img-001').click(function() {
$.fancybox({
type: 'iframe',
href: 'doc-001.html',
showCloseButton: true
});
});
$('#img-002').click(function() {
$.fancybox({
type: 'iframe',
href: 'doc-002.html',
showCloseButton: true
});
});
但是,這樣做很麻煩,並且需要一遍又一遍地復制相同的代碼。 是否有允許使用單個功能的替代方法? 這樣的操作將采用#img-ID
任何內容,並將href
更改為doc-ID.html
。 或者,或者,如何使用一個類來做到這一點(每個元素仍然需要一個特定的鏈接)?
這可能嗎?
這里最簡單的解決方案是
$('[id^="img-"]').click(function() { // select all elements whose id starts with "img-"
$.fancybox({
type: 'iframe',
href: 'doc'+this.id.slice(3)+'.html', // takes the "-007" part of "img-007"
showCloseButton: true
});
});
$('#img-001, #img-002').click(function() {
var code = this.id.replace('img', '');
$.fancybox({
type: 'iframe',
href: 'doc' + code + '.html',
showCloseButton: true
});
});
$('#img-001,#img-002').click(function() {
$.fancybox({
type: 'iframe',
href: 'doc-'+this.id.split['-'][1]+'.html',
showCloseButton: true
});
});
這是我在發布后幾分鍾想到的( mask
是所有元素共享的類):
$('div.mask').click(function() {
var id = $(this).attr('id');
var documentLink = "work-" + id.split("-")[1] + ".html";
$.fancybox({
type: 'iframe',
href: documentLink,
showCloseButton: true
})
}
);
但是我想知道是否有更好的方法來處理documentLink
。
這將指導您:
function magic(){
m = $(this).attr("id").match(/.*-(.*)/)
$.fancybox({
type: 'iframe',
href: 'doc-'+m[1]+'.html',
showCloseButton: true
});
}
並應用於所有圖像或所需的任何選擇器:
$("body").find("img").each(magic);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.