将对象转换为 HTML 元素

Posted

技术标签:

【中文标题】将对象转换为 HTML 元素【英文标题】:Convert object to HTML element 【发布时间】:2016-09-17 06:27:50 【问题描述】:

函数的输入是一个具有这种结构的对象:


  tag: 'a', //type of html object
  content: "blabal", //inner content
  attr: 
    href: "vk.com",
    id: 'someId'
  ,
  events: 
    click: 'alert(this.href)',
    focus: 'this.className="active"'
  ,
  style: 
    width:"100px"
  

它描述了一个 HTML 元素。它必须返回具有指定属性的 HTML 元素。如何解析它?我有这样的事情:

elemen=
  tag:'a',
  content:"blabal",
  attr:
    href:"vk.com",
    id:'someId'
  ,
  events:
   click:'alert(this.href)',
   focus:'this.className="active"'
  ,
  style:
    width:"100px"
  
;
console.log(elemen.tag);
var node = document.createElement(elemen.tag);
node.innerHTML= elemen.content;

for(var prop in elemen.events)

  var fun =new Function(elemen.events[prop]);
  console.log(fun);
  node.bind(prop, fun);
//   divv.bind(prop, fun);

【问题讨论】:

mustache 或 jquery tmpl 等模板是否可以替代? 是的。他只有我描述的结构。没有其他选择 请注意,javascript 对象不是 JSON。 JSON 是一种数据格式,在 JavaScript 中,您只能在字符串中包含 JSON。见What is the difference between JSON and Object Literal Notation? 【参考方案1】:

使用addEventListenerElement.bind(thisArg) 上注册事件以将参数指定为this-context

var elemen = 
  tag: 'a',
  content: "blabal",
  attr: 
    href: "vk.com",
    id: 'someId'
  ,
  events: 
    click: 'alert(this.href)',
    focus: 'this.className="active"'
  
;
var node = document.createElement(elemen.tag);
node.innerHTML = elemen.content;
for (var attr in elemen.attr) 
  node.setAttribute(attr, elemen.attr[attr]);

for (var prop in elemen.events) 
  node.addEventListener(prop, new Function(elemen.events[prop]).bind(node));

document.body.appendChild(node);
.active 
  color: red;

【讨论】:

【参考方案2】:

仅使用 javascript

 var _createElem = document.createElement(""+_elem.tag+""); 
 _createElem.innerHTML = _elem.content;

//set attributes
for(var keys in _elem.attr)
  _createElem.setAttribute(''+keys+'',_elem.attr[keys])
 
//set style 
 for(var keys in _elem.style)
  _createElem.setAttribute(''+keys+'',_elem.style[keys])
 
//set events
for(var keys in _elem.events)
_createElem.setAttribute('on'+keys,_elem.events[keys])
 
document.getElementById("demoDiv").appendChild(_createElem)

注意:elem 有 onclickhref ,您可能需要 return true/false 根据您的要求

【讨论】:

错误的小提琴。所有这些不需要的引号是怎么回事? Don't use onevent HTML attributes.【参考方案3】:

使用以下函数:

const objectToHTML = function(obj) 
  const element = document.createElement(obj.tag)
  element.innerHTML = obj.content
  for (const name in obj.attr) 
    const value = obj.attr[name]
    element.setAttribute(name, value)
  
  for (const name in obj.events) 
    const listener = new Function(obj.events[name]).bind(element)
    element.addEventListener(name, listener)
  
  for (const property in obj.style) 
    const value = obj.style[property]
    element.style[property] = value
  
  return element

要从字符串创建事件侦听器,您必须使用Function constructor 将其转换为函数,使用Function.prototype.bind() 将上下文绑定到它(否则该函数将使用window 作为上下文执行),最后,使用element.addEventListener()

剩下的就很明显了。

你可以这样使用这个函数:

const element = objectToHTML(
  tag: 'a',
  content: "blabal",
  attr: 
    href: "vk.com",
    id: 'someId'
  ,
  events: 
    click: 'alert(this.href)',
    focus: 'this.className="active"'
  ,
  style: 
    width: "100px"
  
)

document.body.appendChild(element)

查看演示:

const objectToHTML = function(obj) 
  const element = document.createElement(obj.tag)
  element.innerHTML = obj.content
  for (const name in obj.attr) 
    const value = obj.attr[name]
    element.setAttribute(name, value)
  
  for (const name in obj.events) 
    const listener = new Function(obj.events[name]).bind(element)
    element.addEventListener(name, listener)
  
  for (const property in obj.style) 
    const value = obj.style[property]
    element.style[property] = value
  
  return element


const element = objectToHTML(
  tag: 'a',
  content: "blabal",
  attr: 
    href: "vk.com",
    id: 'someId'
  ,
  events: 
    click: 'alert(this.href)',
    focus: 'this.className="active"'
  ,
  style: 
    width: "100px"
  
)

document.body.appendChild(element)

【讨论】:

【参考方案4】:

我推荐这种形式,适应性更强。

window.onload = function() 
 
  function init_() 

    function action__(type, element, convert, a) 
      if (type == "function") 
        if (convert.create[a] != null) 
          try 
            var new_ = convert.create[a](element[a]);
           catch (rrr) 
            rrr = (rrr.toString());

            if (rrr.indexOf('2 arguments') != -1 && Object.keys(element[a]).length != 0) 
              for (v in element[a]) 
                convert.create[v] = element[a][v];
                var new_ = convert.create;
              
            ;
          
          convert['create'] = new_;
        

      ;

      if (type == "object") 
        for (f in element[a]) 
          convert.create[a][f] = element[a][f];
        
      

      if (type == "string" && a != "events") 
        convert.create[a] = (element[a]);
       else if (type == "string" && a == "events") 
        for (ev in element[a]) 
          var type = convert.detectType(convert.create, ev);
          if (type == "function") 
            convert.create.addEventListener(ev, new Function(element[a][ev]));
          
        ;
      ;



      return convert.create;
    ;


    function createElement(elements) 

      var finished = [];

      if (typeof elements.tagName == "undefined" && !elements.length) 
        elements = [elements];
      

      for (r = 0; r < elements.length; r++) 
        var element = elements[r];
        if (element) 
          var convert = 
            create: document,
            detectType: function(element, attribute) 
              var type = "string";
              if (typeof element[attribute] != "undefined") 
                type = typeof element[attribute];
              ;
              return type;
            ,
            add: function(new_) 
              if (new_ && new_ != "undefined") 
                this.create = new_;
              
            

          ;

          for (a in element) 

            var type = convert.detectType(convert.create, a);
            var returner = action__(type, element, convert, a);
            convert.add(returner);
          


          finished.push(convert.create);
        ;

      
      return (finished);

    ;

    var minifi_function = init_.toString();
    
    var elements = [
      createElement: 'a', 
      innerHTML: "blabal", 
      setAttribute: 
        href: "vk.com",
        id: 'someId',
        style: "height:200px;"
      ,
      events: 
        click: 'alert(this.href)',
        focus: 'this.className="active"'
      ,
      style: 
        width: "100px"
      
    , 
      createElement: 'div', 
      innerHTML: "see my content", 
      setAttribute: 
        ['data-link']: "vk.com",
        id: 'someId2',
        style: "height:200px;background:red;"
      ,
      events: 
        click: 'prompt("Copy",' + minifi_function + ')',
        focus: 'this.className="activediv"'
      ,
      style: 
        width: "100px"
      
    ];



    var elementos = createElement(elements);
    console.log(elementos);
    for (p = 0; p < elementos.length; p++) 
      document.body.appendChild(elementos[p]);
    

  

  init_();

【讨论】:

以上是关于将对象转换为 HTML 元素的主要内容,如果未能解决你的问题,请参考以下文章

将 jquery 元素转换为 html 元素

如何将具有元素数组的每个对象的对象列表转换为具有子元素作为属性的对象数组

如何将字符串转化为Jsoup的Document 对象

使用 jQuery 将表单数据转换为 JavaScript 对象

如何将字符串对象(包含 XML)“转换”为现有 JSP 页面上的元素

将 JSON 转换为元素树 [关闭]