
RIOT.JS - 訪問 DOM
我們可以使用 ref 物件訪問 HTML 元素。作為第一步,我們向 DOM 元素新增一個 ref 屬性,並透過標籤的指令碼塊中的 this.ref 訪問它。
附加引用 − 向 DOM 元素新增 ref 屬性。
<button ref = "clickButton">Click Me!</button>
使用 refs 物件 − 現在在 mount 事件中使用 refs 物件。此事件在 RIOT 掛載自定義標籤時觸發,並且它填充 refs 物件。
this.on("mount", function() { this.refs.clickButton.onclick = function(e) { console.log("clickButton clicked"); return false; }; })
示例
以下是完整示例。
custom6Tag.tag
<custom6Tag> <form ref = "customForm"> <input ref = "username" type = "text" value = "Mahesh"/> <button ref = "clickButton">Click Me!</button> <input type = "submit" value = "Submit" /> </form> <script> this.on("mount", function() { this.refs.clickButton.onclick = function(e) { console.log("clickButton clicked"); return false; }; this.refs.customForm.onsubmit = function(e) { console.log("Form submitted"); return false; }; }) </script> </custom6Tag>
custom6.htm
<html> <head> <script src = "https://cdnjs.cloudflare.com/ajax/libs/riot/3.13.2/riot+compiler.min.js"></script> </head> <body> <custom6Tag></custom6Tag> <script src = "custom6Tag.tag" type = "riot/tag"></script> <script> riot.mount("custom6Tag"); </script> </body> </html>
這將產生以下結果 −
廣告