Javascript 如何在不复制所有代码的情况下将jquery函数扩展到多个元素?
我用它在点击链接时触发图像打印Javascript 如何在不复制所有代码的情况下将jquery函数扩展到多个元素?,javascript,jquery,Javascript,Jquery,我用它在点击链接时触发图像打印 $(document).ready(function() { $('.print_no_1').bind('click',function() { var thePopup = window.open( '', "Print widnow", "menubar=0,location=0,height=700,width=700" ); $('#print_img_1').clone().appendTo( thePopup.
$(document).ready(function() {
$('.print_no_1').bind('click',function() {
var thePopup = window.open( '', "Print widnow", "menubar=0,location=0,height=700,width=700" );
$('#print_img_1').clone().appendTo( thePopup.document.body );
thePopup.print();
});
});
“title=”“alt=”“/>
我想知道的是,将相同的函数应用于其他三个图像的最佳方法是什么,以避免将孔jquery代码复制三次。您可以执行以下操作:
<img style="" id="print_img_1" src="<?php echo $day_event_print[0]; ?>" title="" alt="" />
<a href="#" class="print_no_1" />click here</a>
for(var i=1;iHtml:
这样,只要点击一个html类“myLink”,javascript就会将其作为父对象并搜索图像,然后对所有对象执行相同的操作。我想这就是您所需要的。谢谢!找到了,我只需在元素的末尾添加数字?
for (var i = 1; i <= 3; ++i) {
(function (n) {
$('.print_no_' + n).bind('click',function() {
var thePopup = window.open( '', "Print widnow", "menubar=0,location=0,height=700,width=700" );
$('#print_img_' + n).clone().appendTo( thePopup.document.body );
thePopup.print();
});
})(i);
}
<div class="myContainer">
<img style="myImage" src="<?php echo $day_event_print[0]; ?>" title="" alt="" />
<a href="#" class="myLink" />click here</a>
</div>
$(document).ready(function() {
$('.myLink').bind('click',function(e) {
e.preventDefault();
var thePopup = window.open( '', "Print widnow", "menubar=0,location=0,height=700,width=700" );
$(this).parent().find('.myImage')[0].clone().appendTo( thePopup.document.body );
thePopup.print();
});
});