压缩Javascript/jQuery代码
Condensing Javascript/jQuery Code
首先,
我要感谢任何可以帮助我压缩这段Javascript/jQuery代码的人。
jQuery(function() {
jQuery('#pitem-1').click(function(e) {
jQuery("#image-1").lightbox_me({centered: true, onLoad: function() {
jQuery("#image-1").find("input:first").focus();
}});
e.preventDefault();
});
jQuery('#pitem-2').click(function(e) {
jQuery("#image-2").lightbox_me({centered: true, onLoad: function() {
jQuery("#image-2").find("input:first").focus();
}});
e.preventDefault();
});
jQuery('#pitem-3').click(function(e) {
jQuery("#image-3").lightbox_me({centered: true, onLoad: function() {
jQuery("#image-3").find("input:first").focus();
}});
e.preventDefault();
});
jQuery('table tr:nth-child(even)').addClass('stripe');
});
基本上每个 #pitem-ID 都会在弹出窗口中打开相同的 #image-ID。
再次感谢任何可以提供帮助的人。
千斤顶
你的函数看起来都差不多,这是一个线索,你可能应该将该功能移到可以调用的东西中:
function createHandler(id) {
return function (e) {
$(id).lightbox_me({centered: true, onLoad: function() {
$(id).find("input:first").focus();
}});
e.preventDefault();
}
};
然后,您可以使用:
$('#pitem-2').bind('click', createHandler("#image-2"));
您可以:
- 使用公共事件处理程序将多个对象合并到选择器中
- 使用
this
引用触发事件的对象 - 从生成事件的对象的 id 派生图像 ID。
这允许您使用一段代码来处理所有三个对象的操作:
jQuery(function() {
jQuery("#pitem-1, #pitem-2, #pitem-3").click(function() {
var image$ = $("#" + this.id.replace("pitem", "image"));
image$.lighbox_me({centered: true, onLoad: function() {
image$.find("input:first").focus();
}});
e.preventDefault();
});
jQuery('table tr:nth-child(even)').addClass('stripe');
});
$('[id^="pitem-"]').click(function(e) {
var numb = this.id.split('-')[1];
$("#image-"+numb).lightbox_me({centered: true, onLoad: function() {
$(this).find("input:first").focus();
}
});
e.preventDefault();
});
$('table tr:nth-child(even)').addClass('stripe');
没有上下文很难说,但是是否有必要为每个pitem
都有一个唯一的 ID?为什么不使用CSS类而不是像这样的ID:
<div class="pitem">
<div id="image1"><img ... /></img>
</div>
...
<div class="pitem">
<div id="image3"><img ... /></img>
</div>
然后使用 jQuery 中的类选择器一次性添加所有点击功能:
$(".pitem").click(function(e) {
var currentItem = e.target;
...
e.preventDefault();
});
相关文章:
- 如何动态插入jquery代码
- 如何在php变量中嵌入JQuery代码
- 将 jQuery 代码添加到 Index.aspx 页面
- 元素在我的代码中不会.fadeTo.Don'I don’我不知道;s错误的JavaScript、JQuery、H
- jquery代码在Mozilla中有效,但在其他浏览器上无效
- Jquery:代码在rails中的页面加载时未执行
- 您有更好的动态方式来缩短复杂的代码jquery吗
- Don't工作警报代码jQuery
- <script src=“//代码.jquery.com/jquery-1.11.1.min.js”></
- 如何确保我的值已添加并存在,然后运行另一个代码jquery
- 命令代码jquery文件错误
- 解释此代码 jQuery
- 使用 JavaScript 编写 HTML 代码 (jquery)
- 将 Ruby 数组传递给 Ruby on Rails 中 Haml 视图中的 JavaScript 代码 (jquery
- 通过国家代码jquery获取时区
- 什么是错误的这个自动完成代码(JQuery-UI自动完成)
- 抓取国家从谷歌地理代码jquery
- 检查列表中的元素是否有来自变量的SRC,然后运行代码- jQuery / Javascript
- 在附加代码jquery中包含附加内容
- 将变量php问题化为代码jquery