如果您使用的是jQuery,则:
HTML:
<a id="openMap" href="/map/">link</a>
JS:
$(document).ready(function() {
$("#openMap").click(function(){
popup('/map/', 300, 300, 'map');
return false;
});
});
这样的好处是仍然可以在没有JS的情况下工作,或者如果用户中间单击了链接。
这也意味着我可以通过再次重写为以下内容来处理通用弹出窗口:
HTML:
<a class="popup" href="/map/">link</a>
JS:
$(document).ready(function() {
$(".popup").click(function(){
popup($(this).attr("href"), 300, 300, 'map');
return false;
});
});
这样,您只需给其弹出窗口类,便可以将弹出窗口添加至任何链接。
这个想法可以像这样进一步扩展:
HTML:
<a class="popup" data-width="300" data-height="300" href="/map/">link</a>
JS:
$(document).ready(function() {
$(".popup").click(function(){
popup($(this).attr("href"), $(this).data('width'), $(this).data('height'), 'map');
return false;
});
});
现在,我可以在整个站点上使用相同的代码来处理大量弹出窗口,而不必编写大量的onclick内容!是的,可重用!
这也意味着,如果以后我认为弹出式窗口是不正确的做法(确实如此),并且希望将其替换为灯箱样式模式窗口,则可以更改:
popup($(this).attr("href"), $(this).data('width'), $(this).data('height'), 'map');
至
myAmazingModalWindow($(this).attr("href"), $(this).data('width'), $(this).data('height'), 'map');
而且我整个网站上的所有弹出窗口现在的工作方式都完全不同。我什至可以进行功能检测来决定对弹出窗口执行的操作,或者存储用户首选项以允许或不允许用户使用。使用内联onclick,这需要大量的复制和粘贴工作。