javascript - DOM 不会根据附加 JQuery 的子标签进行更新

标签 javascript riot.js riot

我正在尝试根据 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/

相关文章:

javascript - 无限水平滚动 Div

javascript - 基于 JavaScript 中的 ascii 代码从字符串中删除字符

javascript - RiotJS : How to cache values during loops?

javascript - 如何在根组件中设置多个类变量

javascript - 是否可以将 javascript 代码与 Riot Js 中的标记文件分开?

java - 从id中获取召唤者名字

javascript - 视频加载栏在阵列上工作

php - Google 如何在不重新加载页面的情况下将搜索参数附加到 url?

javascript - Riot.js 动态呈现来自不同文件服务器端的嵌套自定义标签

javascript - riot js this.update 奇怪的行为