【问题标题】:How to make link into img tag work with ajax如何使链接到 img 标记与 ajax 一起使用
【发布时间】:2021-03-28 21:06:42
【问题描述】:

我有两个脚本,一个将链接转换为 youtube 播放器,它适用于 ajax,现在我想做同样的事情,但使用 img 链接将其转换为 img 标签,而这个不适用于 ajax,我的意思是 ajax 在论坛线程和寻呼机是 ajax 如果你转到下一页它不再工作你必须刷新窗口。

<script>
$(document).ready(function () {
    var r = /^((?:https?:)?\/\/)?((?:www|m)\.)?((?:youtube\.com|youtu.be))(\/(?:[\w\-]+\?v=|embed\/|v\/)?)((?!\bchannel\b)[\w\-]+)([\S]+)?$/;
    function c() {
        $("#content-content a").each(function () {
            var e,
                o,
                t = $(this).attr("href"),
                c = r.exec(t);
            null !== c &&
                (console.log(c[5], c[6]),
                (e = c[5]),
                void 0 !== c[6] && c[6].toLowerCase().includes("t=") && (e += c[6]),
                console.log(e),
                (o = '<iframe width="100%" height="315" src="https://www.youtube.com/embed/{youtubeVideoId}" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>'.replace(
                    "{youtubeVideoId}",
                    e
                )),
                $(this).replaceWith(o));
        });
    }
    c(),
        (Drupal.behaviors.YtUrlToPlayerBehaviour = function (e, o) {
            $(document).ajaxComplete(function (e, o, t) {
                c();
            });
        });
});
</script>

<script>
$('a[href$=".png"], a[href$=".jpg"], a[href$=".gif"], a[href$=".tiff"], a[href$=".webp"]').each(function(){
    $(this).html('<img src="' + $(this).attr('href') + '" />');
});
</script>

【问题讨论】:

    标签: javascript jquery ajax drupal


    【解决方案1】:

    如果仅在页面加载时评估和调用您的脚本(底部与图像有关的内容)。

    Drupal 有一个名为'Drupal.behaviors' 的javascript 对象,它基本上是一个在页面完成加载时将调用的函数列表,即。 '$(document).ready()' 或 ajax 调用完成时。

    您要做的是将您自己的函数附加到此行为列表中,以便在页面加载或某些 ajax 完成时执行您的代码。您可以使用“Drupal.behaviors.YtUrlToPlayerBehaviour”查看其他 youtube 代码。

    如果您想了解更多详情,请阅读herehere

    这段代码可能对你有用。

    Drupal.behaviors.myImageBehavior = {
      attach: function (context, settings) {
        $('a[href$=".png"], a[href$=".jpg"], a[href$=".gif"], a[href$=".tiff"], a[href$=".webp"]', context).each(function(){
          $(this).html('<img src="' + $(this).attr('href') + '" />');
        });
      }
    }
    

    注意“context”变量,在页面加载时这将是文档,但在 ajax 调用之后,它将是 ajax 返回的内容。使用上下文变量确保您的代码仅在当时页面的新内容上运行。

    与大多数 Drupal 和 Javascript 一样,还有其他方法,但上面的代码是您在 Drupal 中执行的标准方式。

    【讨论】:

      猜你喜欢
      • 2021-03-08
      • 2017-08-17
      • 2022-01-23
      • 2014-01-25
      • 1970-01-01
      • 2015-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多