v2.0.3

建構 DOM 元素

最後更新


以標籤選擇器字串建構真實 DOM 元素,並用字串 getter 查詢元素。

第一次渲染:鏈式 DOM 建構


"tag.class#id"._(attrs, children) 依標籤選擇器字串建立真實 DOM 元素,自動處理 SVG 命名空間與 input/textarea 型別解析。#id 片段成為元素的 id;每個 .class 片段會連同開頭的點一起加入 class 列表("p.note"._() 產生 class=".note"),一般 class 名稱請改用 _class() 或 class 屬性設定。jQuery 會把選到的元素包成 jQuery 物件來串接方法;RenderJS 則把方法加在原生 prototype 上,因此 "section#test"._() 與 "test".$ 回傳的是一般的 Element。
  1. <script>
  2. document.body._child(
  3. "section#test"._([
  4. "button"._({
  5. style: {
  6. width: "10rem",
  7. height: "2rem",
  8. backgroundColor: "steelblue",
  9. color: "#fff"
  10. }
  11. }, [
  12. "span"._("test"),
  13. " button"
  14. ])._click(function () {
  15. alert("test");
  16. }),
  17. "img"._({ lazyload: "/assets/cover.png", width: 160 }),
  18. "input@email type"._()
  19. ])
  20. );
  21. // 啟用 SVG 內嵌與圖片延遲載入監聽器
  22. _Listener({
  23. svg: true,
  24. lazyload: true
  25. });
  26. </script>
即時預覽 · @pardnchiu/renderjs@2.0.3

元素查詢


  1. <div id="test">#test</div>
  2. <div class="test">first .test</div>
  3. <div class="test">second .test</div>
  4. <pre id="out"></pre>
  5. <script>
  6. "out".$.textContent = [
  7. '"test".$ -> ' + "test".$.textContent,
  8. '"div.test".$ -> ' + "div.test".$.textContent,
  9. '"div.test".$all -> ' + "div.test".$all.length + " elements"
  10. ].join("\n");
  11. </script>
即時預覽 · @pardnchiu/renderjs@2.0.3

完整方法列表見 String 擴充 與 Element 擴充。
EN