如何在JavaScript中从IMG标记获取ALT

时间:2018-02-05 14:55:42

标签: javascript jquery html wordpress lightbox

我正在使用THIS脚本在灯箱中显示我的画廊。我正在使用一些插件,但所有插件都没有显示alt =""(在wordpress中的媒体中添加了alt)。

如何修改以下链接中的代码以显示alt属性?

我在代码中找到了一些东西,但我不知道如何将动态alt放在那里(在代码中用大写文本注释)。动态我的意思是,当用户将在wordpress仪表板中添加img时,他会将alt设置为。

{
            key: '_preloadImage',
            value: function _preloadImage(src, $containerForImage) {
                var _this4 = this;

                $containerForImage = $containerForImage || false;

                var img = new Image();
                if ($containerForImage) {
                    (function () {

                        // if loading takes > 200ms show a loader
                        var loadingTimeout = setTimeout(function () {
                            $containerForImage.append(_this4._config.loadingMessage);
                        }, 200);

                        img.onload = function () {
                            if (loadingTimeout) clearTimeout(loadingTimeout);
                            loadingTimeout = null;
                            var image = $('<img />');
                            image.attr('src', img.src);
                            image.addClass('img-fluid');
image.attr('alt',"Temp TEXT"); // HERE I WOULD LIKE TO DISPLAY THE ALT AUTOMATICALLY - NOT STATIC AS IT IS NOW

                            // backward compatibility for bootstrap v3
                            image.css('width', '100%');

                            $containerForImage.html(image);
                            if (_this4._$modalArrows) _this4._$modalArrows.css('display', ''); // remove display to default to css property

                            _this4._resize(img.width, img.height);
                            _this4._toggleLoading(false);
                            return _this4._config.onContentLoaded.call(_this4);
                        };
                        img.onerror = function () {
                            _this4._toggleLoading(false);
                            return _this4._error(_this4._config.strings.fail + ('  ' + src));
                        };
                    })();
                }

                img.src = src;
                return img;
            }
        },

我在我的页面上使用wordpress,而我在JS中的技能相当差,所以我问你:)。

2 个答案:

答案 0 :(得分:1)

我们真的不知道您的img变量的类型。如果您要将image的alt标记设置为img的标记,只需执行以下操作:

image.attr('alt', img.attr('alt'));

...如果它是一个jQuery对象。否则,如果img是纯JavaScript,则可以执行以下操作:

image.attr('alt', img.alt);

答案 1 :(得分:0)

如果img对象包含现有的alt并且image是新的jQuery对象,则使用jQuery设置它

image.attr('alt', img.getAttribute('alt'))
相关问题