如何在riot.js中访问子元素 [英] How do I access child elements within riot.js

查看:100
本文介绍了如何在riot.js中访问子元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个自定义的riot标记,其中带有p,如下所示:

If I have a custom riot tag with a p in it like this:

<custom>
  <p>This is a text</p>
</custom>

如何从<custom>标记内访问<p>元素?

How do I access the <p> element from within the <custom> tag?

更新::我收到了一堆答案,可以从DOM中选择它.我想要的是一种从组件库 riot.js 本身中选择内部p标记的方法.我正在寻找一个更特定于riotjs的答案.例如,对于聚合物,您可以使用this.$.content.getDistributedNodes().

Update: I've received a whole bunch answers that are of ways to select it from the DOM. What I want is a way to select the inner p tag from within the component library riot.js itself. I'm looking for a more riotjs specific answer. For example with polymer you use this.$.content.getDistributedNodes().

推荐答案

Riot仅提供4个属性来访问您当前所在标签中的数据:

Riot only provides 4 properties to access data from the current tag you're in:

  • this.opts
  • this.parent
  • this.root
  • this.tags

请参阅API文档

修改

除此之外,您还可以直接访问named elements:

Besides this you can directly access named elements:

<my-tag>
  <p name="foo">Hi, I'm foo</p>
  <script>
    console.log(this.foo);
  </script>
</my-tag>

参见文档

/编辑

没有直接引用您在自定义标记中定义的任何元素; 其余部分归结为纯旧的JS(您可能会喜欢或不喜欢).

There's no direct reference to any of the elements you defined in your custom-tag; the rest comes down to just pure old JS (which you might favour or not).

就像其他人所述,您可以使用dom方法访问元素.但是,在某些情况下,您需要等到实际加载DOM为止.例如:

Like others stated, you can access elements using dom methods. However, in some cases you need to wait until the DOM is actually loaded. For instance:

<my-tag>
  <p>yada</p>
  <script>
    console.log(this.root.querySelector('p'))
  </script>
</my-tag>

无法正常工作,因为DOM尚未准备好.而是将选择器包装在挂载"事件侦听器中,如下所示:

won't work, because the DOM is not ready yet. Instead wrap the selector in a 'mount' event listener like this:

<my-tag>
  <p>yada</p>
  <script>
    this.on('mount', function() {
      console.log(this.root.querySelector('p'))
    })
  </script>
</my-tag>

这篇关于如何在riot.js中访问子元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆