简体   繁体   English

触发 JavaScript 生成链接问题

[英]Firing JavaScript generated link issue

I have issues firing this link (that triggers a script from Chargebee) when is added dynamically via JavaScript.当通过 JavaScript 动态添加时,我在触发此链接(触发 Chargebee 的脚本)时遇到问题。 When it's added directly in html it works normally.直接在html中添加时,正常工作。

The entire generated link is appearing correctly (populated with the variants) in browser when inspected just it doesn't fire.检查时,整个生成的链接在浏览器中正确显示(填充了变体),只是它不会触发。

Here are the pieces I have related to this:以下是我与此相关的部分:

The JavaScript part: JavaScript 部分:

var checkout = document.getElementById("checkout");
         
var link = '<a href="javascript:void(0)" data-cb-type="checkout"' + data-cb-1 + data-cb-2 + data-cb-3'>Order</a>';
 
checkout.innerHTML = link;

A simple div:一个简单的div:

<div id="checkout"></div>

The script from chargebee:来自chargebee的脚本:

<script src="https://js.chargebee.com/v2/chargebee.js" data-cb-site="site-name"></script>

Once you've loaded chargebee.js script it starts to look for a tag a with specific data-cb attributes.一旦你加载了 chargebee.js 脚本,它就会开始寻找带有特定data-cb属性的标签a The script does it one time only.该脚本只执行一次。 If the tag a did not exist in the DOM then, the script does nothing.如果 DOM 中不存在标签a ,那么脚本什么也不做。 When you add the tag a later that makes no effect at all, because a "discovery phase" is over. a您稍后添加标签时,根本没有效果,因为“发现阶段”已经结束。

If you want to have more control over chargebee initialisation process, you should go for "Checkout via API" option provided by the developers.如果您想更好地控制chargebee初始化过程,您应该为开发人员提供的“通过API结帐”选项提供go。

PS There are two hacky solutions: PS有两个hacky解决方案:

  1. You may load Chargebee script after adding tag a to the DOM.您可以在将标签a添加到 DOM 后加载 Chargebee 脚本。
function loadChargebee() {
    var script = document.createElement("script");
    script.src = "https://js.chargebee.com/v2/chargebee.js";
    script.type = "text/javascript";
    document.getElementsByTagName("head")[0].appendChild(script);
}

var checkout = document.getElementById("checkout");
         
var link = '<a href="javascript:void(0)" data-cb-type="checkout"' + data-cb-1 + data-cb-2 + data-cb-3'>Order</a>';
 
checkout.innerHTML = link;

loadChargebee(); // <=== add Chargebee.js

  1. Leave the tag a in the DOM, load the script as usual but modify data attributes as needed after page load:将标签a留在 DOM 中,照常加载脚本,但在页面加载后根据需要修改数据属性:
<a id="beecheckout" href="javascript:void(0)" data-cb-type="checkout" data-cb-1="" data-cb-2="" data-cb-3="">Order</a>

document.getElementById('beecheckout').setAttribute('data-cb-1','new data value');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM