插入 JavaScript (jQuery) 时无法显示 TrustPilot HTML

Cannot show TrustPilot HTML when inserted with JavaScript (jQuery)

如果我直接在 HTML 页面上添加 TrustPilot html 代码,它可以正常工作,但我需要用 jQuery 插入它。我在插入时看到了 HTML 代码,但它没有显示。

  $(window).on('load', function () {
    var el = $('#some-element');

    el.html( trustPilotHtml() );

    function trustPilotHtml() {
      var str = "<div " +
        "class='trustpilot-widget' " +
        "data-locale='en-GB' " +
        "data-template-id='123456' "+
        "data-businessunit-id='123456' " +
        "data-style-height='500px' " +
        "data-style-width='100%' " +
        "data-theme='light' " +
        "data-stars='4,5' " +
        "data-schema-type='Organization'>" +
        "<a " +
        "href='https://some-url.com' target='_blank'>Trustpilot</a> " +
      "</div>";
      return $(str);
    }
});

让元素正确显示的唯一方法是直接插入 HTML 而不是 javascript?

不,这不是唯一的方法。

您应该在 HTML(或接近它)的 HEAD 部分中有一个 bootstrap 脚本。 此脚本负责初始化您在 HTML.

中的所有小部件(Trustpilot 术语中的 TrustBoxes)

当然,如果您动态注入 HTML,那是行不通的,所以您也可以在需要时自己调用 window.Trustpilot.loadFromElement(trustbox);

这里trustbox是一个HTML元素,你可以用document.getElementById("some-element")或类似的方法得到。

参考:https://support.trustpilot.com/hc/articles/115011421468

以下内容在产品列表页面上为我工作,该页面通过 ajax

返回筛选列表
var element = document.getElementsByClassName("trustpilot-widget");
for(var i=0; i<element.length; i++) {
    window.Trustpilot.loadFromElement(element[i]);
}

在第一页加载时,所有产品评论都按预期显示,但如果通过 ajax 调用更新页面(例如使用过滤器),评论将丢失。 运行 ajax 之后的上述代码,重新加载评论