如何从< 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)
答
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