使用内置的DOM方法或原型从HTML字符串创建新的DOM元素 [英] Creating a new DOM element from an HTML string using built-in DOM methods or prototype

查看:142
本文介绍了使用内置的DOM方法或原型从HTML字符串创建新的DOM元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用HTML字符串动态创建元素。这里有一个使用原型和DOM的简单示例:

I'm trying to create an element dynamically using an HTML string. Here's a simple example using both prototype and DOM:

// HTML string
var s = '<li>text</li>';
// DOM
var el1 = document.createElement(s);
// prototype
var el2 = new Element(s);
$('mylist').appendChild(el1);
$('mylist').appendChild(el2);

两种方法在列表中插入一个空列表。

Both approaches insert an empty listitem to the list.

我知道使用原型的元素作为构造函数需要一个tagName和一个可选的attributes参数,但我认为它可能让我传递一个HTML字符串。

I know that using prototype's Element as a constructor requires a tagName and an optional attributes parameter, but I figured it may let me pass in an HTML string too.

但是, MSDN 表示您还可以指定所有属性createElement方法通过使用方法参数的HTML字符串...所以我不知道问题是什么。

However, MSDN states "You can also specify all the attributes inside the createElement method by using an HTML string for the method argument."... so I'm not sure what the problem is.

是的,我知道我可以做这很容易在jquery,不幸的是我们没有使用jquery。我可以俯瞰一些非常简单的东西吗?

And yes, i know i could do this easily in jquery, unfortunately we're not using jquery. Am i overlooking something really simple here?

推荐答案

应该很明显,但是MSDN文章的链接是关于IE的功能

Should be obvious, but the link to that MSDN article is regarding an IE only feature.

通常以下跨浏览器的技巧是所有库都可以从HTML字符串中获取DOM元素(为IE提供了一些额外的工作 < td> s,< tr> s,< thead> s,< select> 等):

Generally the following cross-browser trick is what all the libraries do to get DOM elements from an HTML string (with some extra work for IE for <td>s, <tr>s, <thead>s, <select>s and more):

var s = '<li>text</li>'; // HTML string

var div = document.createElement('div');
div.innerHTML = s;
var elements = div.childNodes;

var element = div.firstChild if你知道你得到一个根节点。

Or var element = div.firstChild if you know you're getting a single root node.

我建议你坚持使用图书馆批准的从HTML字符串创建元素的方法。原型具有内置于其 update()方法

I would recommend you stick to the library-approved method of creating elements from HTML strings though. Prototype has this feature built-into its update() method.

这篇关于使用内置的DOM方法或原型从HTML字符串创建新的DOM元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆