我正在为我的网站使用 Knockout.js 组件。我想在我的一个组件中添加一个 Twitter 关注按钮。您可能知道,Twitter 提供了一个可以使用脚本来完成此操作的代码片段。
<a href="https://twitter.com/vishnu_narang" class="twitter-follow-button" data-show-count="false">Follow
@vishnu_narang</a>
<script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script>
此代码片段应该使用 iframe 以及小部件脚本执行的其他操作来添加 Twitter 关注按钮。
这在组件之外工作得很好。 示例:
<html>
<body>
// Snippet here will work as expected
</body>
</html>
但是在knockout js组件中,它不起作用:
例如:
<html>
<body>
<profile></profile>
</body>
</html>
// Profile template will be
<div>
//snippet for follow button here.
</div>
有人可以帮我找到一种在此类组件中成功添加关注按钮的方法吗?
注意:我还使用 require.js 和 gulp。 Facebook 点赞按钮呈现良好。
最佳答案
Twitter 小部件 JavaScript 一旦加载,就会立即扫描 DOM 以查找需要转换为小部件的元素。由于您在组件中动态加载该元素,因此在 twitter javascript 完成之前,该元素实际上并不存在于 DOM 中。
要解决此问题,您可以通过从组件的 View 模型函数调用 twttr.widgets.load()
来强制小部件再次扫描 dom。 Reference
示例:jsFiddle
关于javascript - 如何在knockout js组件中添加twitter关注按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42197592/