0

这是我当前的代码:

document.getElementsByName('links')[0].onclick = function (event) {
event = event || window.event;
var target = event.target || event.srcElement,
    link = target.src ? target.parentNode : target,
    options = {index: link, event: event},
    links = this.getElementsByTagName('a');
blueimp.Gallery(links, options);
};

document.getElementsByName('links')[1].onclick = function (event) {
event = event || window.event;
var target = event.target || event.srcElement,
    link = target.src ? target.parentNode : target,
    options = {index: link, event: event},
    links = this.getElementsByTagName('a');
blueimp.Gallery(links, options);
};

我意识到这种复制和粘贴非常低效(当我需要添加[2].onclick,[3].onclick等时只会变得更糟),那么有没有办法可以将它们全部压缩在一起?

我是 Javascript 的初学者,所以如果这个问题非常简单,请原谅我。

4

1 回答 1

0

除了 jQuery,您需要做的就是封装重复的代码,例如:

<script>
var elements = document.getElementsByName('links');
Array.prototype.forEach.call(elements, function (el) {
    el.onclick = function (event) {
        event = event || window.event;
        var target = event.target || event.srcElement,
            link = target.src ? target.parentNode : target,
            options = {index: link, event: event},
            links = this.getElementsByTagName('a');
        blueimp.Gallery(links, options);
    };
});
</script>
于 2016-05-14T10:14:54.487 回答