在调用函数中包装脚本

Wrapping a script in a call function

我目前正在使用一个脚本,问题是我必须在每个 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 给出答案,即使你的示例代码没有使用它。

这是一个 fiddle: 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')
        });
    });
});

试一试。