📄 dom.rst
字号:
.. title:: MochiKit.DOM - painless DOM manipulation APIName====MochiKit.DOM - painless DOM manipulation APISynopsis========:: var rows = [ ["dataA1", "dataA2", "dataA3"], ["dataB1", "dataB2", "dataB3"] ]; row_display = function (row) { return TR(null, map(partial(TD, null), row)); } var newTable = TABLE({'class': 'prettytable'}, THEAD(null, row_display(["head1", "head2", "head3"])), TFOOT(null, row_display(["foot1", "foot2", "foot3"])), TBODY(null, map(row_display, rows))); // put that in your document.createElement and smoke it! swapDOM(oldTable, newTable);Description===========As you probably know, the DOM APIs are some of the most painful Java-inspiredAPIs you'll run across from a highly dynamic language. Don't worry about thatthough, because they provide a reasonable basis to build something thatsucks a lot less.MochiKit.DOM takes much of its inspiration from Nevow's [1]_ stan [2]_.This means you choose a tag, give it some attributes, then stuff it fullof *whatever objects you want*. MochiKit.DOM isn't stupid, it knows thata string should be a text node, and that you want functions to be called,and that ``Array``-like objects should be expanded, and stupid ``null`` valuesshould be skipped.Hell, it will let you return strings from functions, and use iterators from:mochiref:`MochiKit.Iter`. If that's not enough, just teach it new tricks with:mochiref:`registerDOMConverter`. If you have never used an API like this forcreating DOM elements, you've been wasting your damn time. Get with it!Dependencies============- :mochiref:`MochiKit.Base`- :mochiref:`MochiKit.Iter`Overview========DOM Coercion Rules------------------In order of precedence, :mochiref:`createDOM` coerces given arguments to DOMnodes using the following rules:1. Functions are called with a ``this`` of the parent node and their return value is subject to the following rules (even this one).2. ``undefined`` and ``null`` are ignored.3. Iterables (see :mochiref:`MochiKit.Iter`) are flattened (as if they were passed in-line as nodes) and each return value is subject to all of these rules.4. Values that look like DOM nodes (objects with a ``.nodeType > 0``) are ``.appendChild``'ed to the created DOM fragment.5. Strings are wrapped up with ``document.createTextNode``6. Objects that are not strings are run through the ``domConverters`` :mochiref:`MochiKit.Base.AdapterRegistry` (see :mochiref:`registerDOMConverter`). The value returned by the adapter is subject to these same rules (e.g. adapters are allowed to return a string, which will be coerced into a text node).7. If no adapter is available, ``.toString()`` is used to create a text node.Creating DOM Element Trees--------------------------:mochiref:`createDOM` provides you with an excellent facility for creating DOM treesthat is easy on the wrists. One of the best ways to understand how to useit is to take a look at an example:: var rows = [ ["dataA1", "dataA2", "dataA3"], ["dataB1", "dataB2", "dataB3"] ]; row_display = function (row) { return TR(null, map(partial(TD, null), row)); } var newTable = TABLE({'class': 'prettytable'}, THEAD(null, row_display(["head1", "head2", "head3"])), TFOOT(null, row_display(["foot1", "foot2", "foot3"])), TBODY(null, map(row_display, rows))); This will create a table with the following visual layout (if itwere inserted into the document DOM): +--------+--------+--------+ | head1 | head2 | head3 | +========+========+========+ | dataA1 | dataA2 | dataA3 | +--------+--------+--------+ | dataB1 | dataB2 | dataB3 | +--------+--------+--------+ | foot1 | foot2 | foot3 | +--------+--------+--------+Corresponding to the following HTML:: <table class="prettytable"> <thead> <tr> <td>head1</td> <td>head2</td> <td>head3</td> </tr> </thead> <tfoot> <tr> <td>foot1</td> <td>foot2</td> <td>foot3</td> </tr> </tfoot> <tbody> <tr> <td>dataA1</td> <td>dataA2</td> <td>dataA3</td> </tr> <tr> <td>dataB1</td> <td>dataB2</td> <td>dataB3</td> </tr> </tbody> </table>DOM Context-----------In order to prevent having to pass a ``window`` and/or ``document``variable to every MochiKit.DOM function (e.g. when working with achild window), MochiKit.DOM maintains a context variable for eachof them. They are managed with the :mochiref:`withWindow` and:mochiref:`withDocument` functions, and can be acquired with:mochiref:`currentWindow()` and :mochiref:`currentDocument()`For example, if you are creating DOM nodes in a child window, youcould do something like this:: withWindow(child, function () { var doc = currentDocument(); appendChildNodes(doc.body, H1(null, "This is in the child!")); });Note that :mochiref:`withWindow(win, ...)` also implies:mochiref:`withDocument(win.document, ...)`.Element Visibility------------------The :mochiref:`hideElement` and :mochiref:`showElement` functions areprovided as a convenience, but only work for elements that are``display: block``. For a general solution to showing, hiding, and checkingthe explicit visibility of elements, we recommend using a solution thatinvolves a little CSS. Here's an example:: <style type="text/css"> .invisible { display: none; } </style> <script type="text/javascript"> function toggleVisible(elem) { toggleElementClass("invisible", elem); } function makeVisible(elem) { removeElementClass(elem, "invisible"); } function makeInvisible(elem) { addElementClass(elem, "invisible"); } function isVisible(elem) { // you may also want to check for // getElement(elem).style.display == "none" return !hasElementClass(elem, "invisible"); }; </script>MochiKit doesn't ship with such a solution, because there is no reliable andportable method for adding CSS rules on the fly with JavaScript.API Reference=============Functions---------:mochidef:`$(id[, ...])`: An alias for :mochiref:`getElement(id[, ...])`:mochidef:`addElementClass(element, className)`: Ensure that the given ``element`` has ``className`` set as part of its class attribute. This will not disturb other class names. ``element`` is looked up with :mochiref:`getElement`, so string identifiers are also acceptable.:mochidef:`addLoadEvent(func)`: Note that :mochiref:`addLoadEvent` can not be used in combination with :mochiref:`MochiKit.Signal` if the ``onload`` event is connected. Once an event is connected with :mochiref:`MochiKit.Signal`, no other APIs may be used for that same event. This will stack ``window.onload`` functions on top of each other. Each function added will be called after ``onload`` in the order that they were added.:mochidef:`addToCallStack(target, path, func[, once])`: Note that :mochiref:`addToCallStack` is not compatible with :mochiref:`MochiKit.Signal`. Once an event is connected with :mochiref:`MochiKit.Signal`, no other APIs may be used for that same event. Set the property ``path`` of ``target`` to a function that calls the existing function at that property (if any), then calls ``func``. If ``target[path]()`` returns exactly ``false``, then ``func`` will not be called. If ``once`` is ``true``, then ``target[path]`` is set to ``null`` after the function call stack has completed. If called several times for the same ``target[path]``, it will create a stack of functions (instead of just a pair).:mochidef:`appendChildNodes(node[, childNode[, ...]])`: Append children to a DOM element using the `DOM Coercion Rules`_. ``node``: A reference to the DOM element to add children to (if a string is given, :mochiref:`getElement(node)` will be used to locate the node) ``childNode``...: All additional arguments, if any, will be coerced into DOM nodes that are appended as children using the `DOM Coercion Rules`_. *returns*: The given DOM element:mochidef:`computedStyle(htmlElement, cssProperty, mozillaEquivalentCSS)`: Looks up a CSS property for the given element. The element can be specified as either a string with the element's ID or the element object itself.:mochidef:`createDOM(name[, attrs[, node[, ...]]])`: Create a DOM fragment in a really convenient manner, much like Nevow`s [1]_ stan [2]_. Partially applied versions of this function for common tags are available as aliases: - ``A`` - ``BUTTON`` - ``BR`` - ``CANVAS`` - ``DIV`` - ``FIELDSET`` - ``FORM`` - ``H1`` - ``H2`` - ``H3`` - ``HR`` - ``IMG`` - ``INPUT`` - ``LABEL`` - ``LEGEND`` - ``LI`` - ``OL`` - ``OPTGROUP`` - ``OPTION`` - ``P`` - ``PRE`` - ``SELECT`` - ``SPAN`` - ``STRONG`` - ``TABLE`` - ``TBODY`` - ``TD`` - ``TEXTAREA`` - ``TFOOT`` - ``TH`` - ``THEAD`` - ``TR`` - ``TT`` - ``UL`` See `Creating DOM Element Trees`_ for a comprehensive example. ``name``: The kind of fragment to create (e.g. 'span'), such as you would pass to ``document.createElement``. ``attrs``: An object whose properties will be used as the attributes (e.g. ``{'style': 'display:block'}``), or ``null`` if no attributes need to be set. See :mochiref:`updateNodeAttributes` for more information. For convenience, if ``attrs`` is a string, ``null`` is used and the string will be considered the first ``node``. ``node``...: All additional arguments, if any, will be coerced into DOM nodes that are appended as children using the `DOM Coercion Rules`_. *returns*: A DOM element:mochidef:`createDOMFunc(tag[, attrs[, node[, ...]]])`: Convenience function to create a partially applied createDOM function. You'd want to use this if you add additional convenience functions for creating tags, or if you find yourself creating a lot of tags with a bunch of the same attributes or contents. See :mochiref:`createDOM` for more detailed descriptions of the arguments. ``tag``: The name of the tag ``attrs``: Optionally specify the attributes to apply ``node``...: Optionally specify any children nodes it should have *returns*: function that takes additional arguments and calls :mochiref:`createDOM`:mochidef:`currentDocument()`: Return the current ``document`` `DOM Context`_. This will always be the same as the global ``document`` unless :mochiref:`withDocument` or :mochiref:`withWindow` is currently executing.:mochidef:`currentWindow()`: Return the current ``window`` `DOM Context`_. This will always be the same as the global ``window`` unless :mochiref:`withWindow` is
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -