如何在不复制所有代码的情况下将jquery函数扩展到多个元素?

时间:2014-04-02 17:15:36

标签: 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.body );
        thePopup.print();
    });
});

当我点击链接时,我用它来触发图像的打印

<img style="" id="print_img_1" src="<?php echo $day_event_print[0]; ?>" title="" alt="" />
<a href="#" class="print_no_1" />click here</a>

我想知道的是,将同一个函数应用于其他三个图像的最佳方法是避免三次复制孔jquery代码。

2 个答案:

答案 0 :(得分:1)

你可以这样做:

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);
}

答案 1 :(得分:0)

HTML:

<div class="myContainer">
<img style="myImage" src="<?php echo $day_event_print[0]; ?>" title="" alt="" />
<a href="#" class="myLink" />click here</a>
</div>

JS:

$(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();
    });
});

有了这个,点击一个html类“myLink”,javascript将获取它的父级并搜索图像,然后对所有人执行相同的行为。我想是你需要的。