我想在#new-post
上添加class属性,它是<script type="text/template" id="template"></script>
的内容
下面是我的代码,它能够找到"template"的内容,但无法添加class属性。
$('#template').contents().find('#new-post').addClass('hello');
HTML
<script type="text/template" id="template">
<div id="new-post">
</div>
</script>
脚本元素包含CDATA,它不能有子元素(<
并不意味着它内部的"标记的开始"(除非该标记是</script>
))。
如果要对模板的内容执行DOM操作,则必须首先将模板解析为DOM。
var template = $('#template').text();
var $template = $(template);
$template.addClass('hello');
alert($template.wrap('<div></div>').parent().html());
为什么不将模板呈现到dom,然后添加类。
编辑:请注意,即使div在普通html标记中,您的代码也无法工作。
请参考这把小提琴:http://jsfiddle.net/shyamchandranmec/R7g3S/
$('#foo').contents().find('#bar').addClass('fb');
$("#foo").find("#bar").addClass('foobar');
<div id="foo">
<div id="bar">foo bar</div>
</div>
类fb不会被添加到div#栏中。