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

Syl*_*lar 1 javascript jquery trustpilot

如果我直接在 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);
    }
});
Run Code Online (Sandbox Code Playgroud)

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

Rck*_*rkr 5

不,这不是唯一的方法。

您应该在 HTML 的 HEAD 部分内部(或靠近它)有一个引导脚本。此脚本负责初始化 HTML 中的所有小部件(Trustpilot 行话中的 TrustBoxes)。

当然,如果您动态地注入 HTML,这将不起作用,因此也可以在window.Trustpilot.loadFromElement(trustbox);需要时调用自己。

trustbox是一个 HTMLElement,您可以通过使用document.getElementById("some-element")或类似的方式获得。

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