我正在构建一个网站,我想运行一个次要的功能,当“添加到购物车”按钮被点击。
由于某种原因,当我尝试使用任何类型的事件侦听器或getElementsbyTagName访问BuyButton脚本创建的按钮时,它总是以未定义的形式返回,并给出以下错误:
未定义TypeError:无法设置未定义(设置'innerHTML')的属性
这是我的密码:
<script src="http://sdks.shopifycdn.com/buy-button/1.0.0/buybutton.js" ></script>
</head>
<body>
<div id="shopifyDiv"></div>
<script type="text/javascript">
/*<![CDATA[*/
var client = ShopifyBuy.buildClient({
domain: 'shopify.myshopify.com',
storefrontAccessToken: '(myTokenHere)',
});
var ui = ShopifyBuy.UI.init(client);
ui.createComponent('product', {
id: (myIdHere),
node: document.getElementById('shopifyDiv'),
options: {
product:{
width: '350px',
contents:{
img: false,
button: true,
title: false
},
text: {
button: 'Add to cart'
},
},
cart:{
startOpen: false
},
}
});
/*]]>*/
</script>
<script type="module">
document.getElementsByTagName('button')[0].innerHTML = 'hello world';
</script>
</body>
</html>为了安全起见,我删除了Shopify特定的accessToken &域名。
任何帮助理解为什么这些由Shopify脚本创建的DOM元素都是不可访问的,我们将不胜感激。
发布于 2022-02-03 22:10:55
Shopify BuyButton在元素中生成iframe。
这意味着两件事:
因此,您需要将一个.then链接到组件创建方法,如下所示:
ui.createComponent('product', {
// your original code
}).then((res) => {
const iframe = document.querySelector('#shopifyDiv iframe').contentDocument;
iframe.querySelector('button').innerHTML = 'hello world';
});一个目标,iframe内容在里面,然后做你的逻辑。
这就是你所要做的。
https://stackoverflow.com/questions/70978076
复制相似问题