我正在尝试根据 API 调用的结果动态附加子 riot.js 标签。每当我尝试使用 jquery 的 .append()
函数附加这些标签时,DOM 不会更新。我尝试了此 github 线程中描述的以下方法(这对我不起作用):
https://github.com/riot/riot/issues/2279
var myTag = document.createElement('my-tag')
$('#container').append(myTag)
riot.mount(myTag)
这是我正在尝试执行的操作的简化示例(下面也列出了代码):https://jsfiddle.net/7m2z7cus/12/
<html>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script src="https://rawgit.com/riot/riot/master/riot.min.js"></script>
</head>
<body>
<foo></foo>
<script>
riot.tag('bar', '<h1>hello</h1>', '', '', function(opts) { });
riot.tag('foo', '<div id="bars"></div>', '', '', function(opts) {
var bar = document.createElement('bar');
$('#bars').append(bar);
riot.mount(bar);
});
riot.mount('foo');
</script>
</body>
</html>
我希望 #bars
div 附加一个 bar
标签,在屏幕上显示“Hello”,但它不在那里。该页面是空白的。我应该如何像上面的示例一样动态附加嵌套标签?
最佳答案
您尝试做的事情是完全可能的,并且您的实现非常接近工作。
唯一缺少的是标签 foo
需要完全安装,然后才能引用标签内的 DOM 节点,即尝试引用 $('#bars')<如果
将不会引用任何内容。foo
未完全安装,
因此,为了使其正常工作,您需要在安装 foo
后创建并附加标签 bar
,这是通过利用 '安装'
事件
对于标签 foo
。
<html>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script src="https://rawgit.com/riot/riot/master/riot.min.js"></script>
</head>
<body>
<foo></foo>
<script>
riot.tag('bar', '<h1>hello</h1>', '', '', function(opts) { });
riot.tag('foo', '<div id="bars"></div>', '', '', function(opts) {
this.on('mount', function() {
// foo has fully mounted. DOM Nodes are accessible inside this callback
var bar = document.createElement('bar');
$('#bars').append(bar);
riot.mount('bar');
})
});
riot.mount('foo');
</script>
</body>
这是 JSFiddle:https://jsfiddle.net/ypwwma2s/
关于javascript - DOM 不会根据附加 JQuery 的子标签进行更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49560075/