jQuery:元素数组到原始 html?
假设我有一个像这样的数组:
var content = [ $('<p>...</p>'), $('<p>...</p>') ];
我需要获取连接元素的标记。所以我需要将 ... ...content
" 转换为原始字符串: "
”。
这怎么能轻松完成?似乎框架中应该已经有一些东西可以做到这一点。
也许可以将 content
转换为文档片段并调用 .html() 在文档片段上获取标记?
Let's say I have an array like this:
var content = [ $('<p>...</p>'), $('<p>...</p>') ];
I need to get the markup of the concatenated elements. So I need to convert content
" into a raw string: "<p>...</p><p>...</p>
".
How can this easily be done? Seems like there should already be something in the framework to do this.
Somehow maybe convert content
into a document fragment and call .html()
on the document fragment to get the markup?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
没有什么是自动的,但您可以轻松地执行您刚才描述的操作。
尝试一下: http://jsfiddle.net/Y5x5z/
Nothing automatic, but you could easily do what you just described.
Try it out: http://jsfiddle.net/Y5x5z/
这比其他答案更短,工作正常,并且不使用显式循环:
正如 Crazy Train 在评论中指出的那样,这可以按如下方式进行糖化:
This is shorter than the other answers, works correctly, and does not use an explicit loop:
As Crazy Train points out in the comments, this can be sugared-up as follows:
我最近遇到了相同类型的任务,今天的方法很简单:
请注意,
reduce
中HTMLString
的默认值是''
。HTMLString
是一种能够将元素的 HTML 字符串连接到它的字符串类型,这一点很重要。I recently encountered the same type of task and today's way of doing this is simple:
Notice that
HTMLString
's default value inreduce
is''
. It's important forHTMLString
to be a type of string to be able to concatenate HTML strings of elements to it.这是一篇旧文章,有人可能会像我一样偶然发现它......正确的方法是 .join() (标准 JavaScript 而非 jQuery)
This is an old post someone may stumble upon it like me... the correct way to do it would be .join() (standard JavaScript not jQuery)