如果我的自定义riot
标记中包含p
,请执行以下操作:
<custom>
<p>This is a text</p>
</custom>
如何从<p>
代码中访问<custom>
元素?
更新:我收到了一大堆答案,可以从DOM中选择它。我想要的是一种从组件库riot.js本身中选择内部p
标签的方法。我正在寻找更具骚动的具体答案。例如,polymer使用this.$.content.getDistributedNodes()
。
答案 0 :(得分:15)
Riot仅提供4个属性来访问您当前标记中的数据:
修改强>
除此之外,您还可以直接访问named elements
:
<my-tag>
<p name="foo">Hi, I'm foo</p>
<script>
console.log(this.foo);
</script>
</my-tag>
<强> /修改
没有直接引用您在自定义标记中定义的任何元素; 其余部分归结为纯粹的旧JS(您可能不喜欢或不喜欢)。< / p>
与其他人一样,您可以使用dom方法访问元素。但是,在某些情况下,您需要等到实际加载DOM。例如:
<my-tag>
<p>yada</p>
<script>
console.log(this.root.querySelector('p'))
</script>
</my-tag>
没有工作,因为DOM还没有准备好。而是将选择器包裹在“#mount”中。像这样的事件监听器:
<my-tag>
<p>yada</p>
<script>
this.on('mount', function() {
console.log(this.root.querySelector('p'))
})
</script>
</my-tag>
答案 1 :(得分:7)
如果您在内部代码中添加了id或name属性,则可以通过self
访问它。
// with 'id'
<custom><p id="pTest">Test</p></custom>
// with 'name'
<custom><p name="pTest">Test</p></custom>
在js部分:
self = this
self.pTest
>> <p id=pTest>Test</p>
在Riot v2.0.10中测试
答案 2 :(得分:4)
请参阅Tag instance。
我们可以访问children
。
customTagAndLoops = this.children
还通过root
向DOM发送。
iAmDom = this.root
childNodes = this.root.childNodes
p = this.root.querySelector('p')
更新 - 2015年2月14日
children
属性已在Riot.js v2.0.9中废弃。访问子元素的唯一方法是使用root
。
答案 3 :(得分:1)
最新版本的Riotjs具有Yielding nested HTML
功能。
See the API docs
在您的情况下,您可以通过这种方式轻松完成:
在代码定义中:
<custom>
<!-- tag markup-->
<div id="place for custom html">
<yield/>
</div>
</custom>
在您的应用中:
<custom>
<p>This is a text</p>
</custom>
呈现的HTML:
<custom>
<div id="place for custom html">
<p>This is a text</p>
</div>
</custom>
来自文档
<yield>
标记还提供了一种插槽机制,允许您在模板中的特定插槽上注入html内容
答案 4 :(得分:1)
在riot 3.4.2中,你可以为你想要的内部元素添加一个ref属性:
<custom>
<p ref="myP">This is a text</p>
</custom>
...
// in js
this.refs.myP
答案 5 :(得分:0)
你试过了吗?
nodes = document.getElementsByTagName('custom');
for (var i = 0; i< nodes.length; ++i) {
paragraphs = nodes[i].getElementsByTagName('p');
alert(paragraphs[0].innerText);
}
getElementsByTagName
会返回一个HTML集合,您可以进一步查询:https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection
这是一个快速而又肮脏的小提琴:http://jsfiddle.net/markm/m8n3huLn/
答案 6 :(得分:0)
querySelector似乎适用于自定义标记:
document.querySelector('custom p').innerHTML= 'Test complete';
&#13;
<p>This is a test</p>
<custom>
<p>This is a test</p>
</custom>
<p>This is a test</p>
&#13;
答案 7 :(得分:0)
如果我理解你的困境,RiotJs Cheatsheet建议使用收益率。
主要标签声明:
<element-i-will-call>
<span>I am a title</span>
<element-child-as-container>
<yield to='header'>Hello User</yield>
<yield to='conent'>You are here</yield>
</element-child-as-container>
</element-i-will-call>
子标签声明:
<element-child-as-container>
<h2>
<yield from='header'/>
</h2>
<div>
<yield from='conent'/>
</div>
</element-child-as-container>
主要实施:
<html>
<head>
...
</head>
<body>
<element-i-will-call />
</body>
</html
答案 8 :(得分:0)
https://riot.js.org/api/#-yielding-nested-html
如果您的html中包含此代码:
<custom>
<p>This is a text</p>
</custom>
然后可以在标签文件中使用<yield/>
<custom>
<yield/>
</custom>
这将使<p>
在页面上呈现