将脚本包装在调用函数中

Wrapping a script in a call function

本文关键字:函数 调用 脚本 包装      更新时间:2023-09-26

我当前有一个脚本im,问题是我必须在每个html img标签之后直接添加脚本。因此,在整个站点的几个不同位置都有相同的脚本。我想知道是否可以将此脚本包装在一个简单的函数调用中,我可以在整个站点中添加该函数而不是整个脚本。

编辑:我应该提到。这是Tumblr主题的灯箱。 photo_{PostID} 有效。photo_{PostID} 检索唯一的照片标识符,以便灯箱显示正确的图像。毫无疑问,脚本现在 100% 完美运行。我希望将其全部转换为一个简单的 1 行调用函数来使用,而无需在每个 img 标签之后粘贴脚本。脚本如下,谢谢。

    <script class="inline_embed" type="text/javascript">
        var domain = document.domain,
        photo_{PostID} = [{
            "width": "{PhotoWidth-HighRes}",
            "height": "{PhotoHeight-HighRes}",
            "low_res": "{PhotoURL-250}",
            "high_res": "{PhotoURL-HighRes}"
        }];
        function event_is_alt_key(e) {
            return ((!e && window.event && (window.event.metaKey || window.event.altKey)) || (e && (e.metaKey || e.altKey)));
        };
        document.getElementById('photo_{PostID}').onclick = function (e) {
            if (event_is_alt_key(e)) return true;
            window.parent.Tumblr.Lightbox.init(photo_{PostID});
            return false;
        }
    </script>

你用 [jquery] 标记了这个问题,所以我将使用 jquery 给出答案,即使你的示例代码不使用它。

这是一个小提琴:http://jsfiddle.net/u2f2b5qq/

给定页面上的一些图像,如下所示:

<img src="http://placehold.it/250x150">
<img src="http://placehold.it/200x250">
<img src="http://placehold.it/350x150">
<img src="http://placehold.it/150x50">

页面加载后,您可以对所有这些执行一些操作,如下所示:

$(function() {
    $('img').each(function() {
        $(this).on('click', function() {
            alert('You clicked ' + $(this).attr('src'));
            // window.parent.Tumblr.Lightbox.init(this);
        });
    });
});

我所做的是将click处理程序附加到每个图像,并在单击时alert。您可以将其替换为灯箱代码。


我并不完全了解 tumblr 如何通过插值来发挥其魔力,但我认为您可以为每个图像做这样的事情。它将照片数据附加到每个图像元素,然后在以后检索它。

<img src="example.jpg" id="photo_{PostID}" data-width="{PhotoWidth-HighRes}" data-height="{PhotoHeight-HighRes}" data-low_res="{PhotoURL-250}" data-high_res="{PhotoURL-HighRes}" />

然后在jquery启动时:

$(function() {
    $('img').on('click', function() {
        var $img = $(this);
        alert('You clicked ' + $img.attr('src'));
        window.parent.Tumblr.Lightbox.init({
            width: $img.data('width'),
            height: $img.data('height'),
            low_res: $img.data('low_res'),
            high_res: $img.data('high_res')
        });
    });
});

一试。