【问题标题】:with zepto created html object does not get an id使用 zepto 创建的 html 对象没有获得 id
【发布时间】:2023-05-23 09:03:01
【问题描述】:

当我使用 zepto.js 从 HTML 字符串创建元素时:

element = $("<ul />", {id:"myID"});
console.log(element);

id "myID" 没有被添加到元素中。控制台输出是这样的:

[<ul></ul>]

根据http://zeptojs.com/ -> $() 它应该得到一个id:

>// create element with attributes:
>$("<p />", { text:"Hello", id:"greeting", css:{color:'darkblue'} })
>//=> <p id=greeting style="color:darkblue">Hello</p>

知道出了什么问题吗?或者这可能是一个错误?

编辑:

我自己是这样解决的:

element.attr('id', 'myID');

虽然最好不要像这样多走一步......

【问题讨论】:

    标签: javascript dom zepto


    【解决方案1】:

    似乎Zepto.js (1.0rc1)版本没有引入这个api。

    参见tag v1.0rc1中的line 152line 100-108

    dom = zepto.fragment(selector.trim(), RegExp.$1), selector = null
    
      zepto.fragment = function(html, name) {
        if (name === undefined) name = fragmentRE.test(html) && RegExp.$1
        if (!(name in containers)) name = '*'
        var container = containers[name]
        container.innerHTML = '' + html
        return $.each(slice.call(container.childNodes), function(){
          container.removeChild(this)
        })
      }
    

    167行110-128行master

    dom = zepto.fragment(selector.trim(), RegExp.$1, context), selector = null
    
      zepto.fragment = function(html, name, properties) {
        if (html.replace) html = html.replace(tagExpanderRE, "<$1></$2>")
        if (name === undefined) name = fragmentRE.test(html) && RegExp.$1
        if (!(name in containers)) name = '*'
    
        var nodes, dom, container = containers[name]
        container.innerHTML = '' + html
        dom = $.each(slice.call(container.childNodes), function(){
          container.removeChild(this)
        })
        if (isPlainObject(properties)) {
          nodes = $(dom)
          $.each(properties, function(key, value) {
            if (methodAttributes.indexOf(key) > -1) nodes[key](value)
            else nodes.attr(key, value)
          })
        }
        return dom
      }
    

    另请阅读issue。也许它会在 1.0 大的时候引入。

    现在,在 api 可以工作之前,您可以使用以下代码执行此操作:

    element = $("<ul />").attr({id:"myID"});
    

    【讨论】:

      最近更新 更多