如何从< template>中选择元素用jQuery [英] How to select elements from <template> with jQuery

查看:78
本文介绍了如何从< template>中选择元素用jQuery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个相似的选择。第一个使用< div> 标记,工作正常,第二个使用新的< template> 标记,它不再起作用。

I have two similar selections. The first uses a <div> tag, which works fine, the second uses a newly <template> tag, which doesn't work anymore.

任何人都可以告诉我如何使用使用jQuery < template> 代码?

Can anyone tell me how to get this to work with jQuery using the <template> tag?

HTML

<div id="div">
    <div>content</div>
</div>

<template id="template">
    <div>content</div>
</template>

JavaScript

var $div = $('#div');
var $content = $div.find('div');
console.log($content); //works ($content.length == 1)

var $template = $('#template');
var $content = $template.find('div');
console.log($content); //doesn't work ($content.length == 0)






http://jsfiddle.net/s8b5w0Le/1/

推荐答案

HTMLTemplateElement将DOM保存为单独的属性:

HTMLTemplateElement saves the DOM into a seperate attribute:

JQuery

<script src="jquery-3.1.0.js"></script>
<script type="text/javascript">
    $(document).ready(function()
    {
        var $div = $('#div');
        var $content = $div.find('div');
        console.log($content.text()); // output "content", inner div

        var $template = $('#template');
        var node = $template.prop('content');
        var $content = $(node).find('div');
        console.log($content.text()); // output "content", inner template
    });

JavaScript

document.createElement('template').content

这篇关于如何从&lt; template&gt;中选择元素用jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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