我不能做什么这2行的意思是:这些Jquery选择器是什么意思?
var template = $("#" + model + " #grid #template").clone();
var templateHtml = $("#templatebody", template).html();
我无法理解的选择这儿过得知道的clone()和HTML()做
我不能做什么这2行的意思是:这些Jquery选择器是什么意思?
var template = $("#" + model + " #grid #template").clone();
var templateHtml = $("#templatebody", template).html();
我无法理解的选择这儿过得知道的clone()和HTML()做
$("#" + model + " #grid #template")
这是元素ID grid
,内部和元件与在所述model
变量中设置的内部id
寻找具有的template
的id
的元件。
例如,如果model
是字符串: '容器':
<div id="container">
<div id="grid">
<div id="template"></div> <!-- this div would be selected -->
</div>
</div>
$("#templatebody", template)
这是一个 '语境' 选择器;它正在查找template
变量中包含的元素内的#templatebody
元素。请注意,在这种情况下,上下文选择器无关紧要,因为在给定页面中应该只有一个元素,且集合为id
。
例
var template = $("#container"); // note - can also be a string: "#container"
$("#templatebody", template)
<div id="container">
<div id="templatebody"></div> <!-- this div would be selected -->
</div>
第一,3号的在选择器?感觉有点矫枉过正。但是你所做的是你克隆了#template
,并从克隆中找到了一个id为#templatebody
的孩子,并取出其HTML内容。你不需要克隆它来获取HTML文本。
// Find the #template that is a child of #grid and #grid is a child of #<insertModel> and clone it
var template = $("#" + model + " #grid #template").clone();
// Find #templatebody child of template (http://api.jquery.com/jQuery/#jQuery2) and get the HTML text thats in #templatebody
var templateHtml = $(“#templatebody”,template).html();
如果你有一个标记看起来像:
<div id="model">
<div id="grid">
<div id="template"><b>Hi</b> there!</div>
</div>
</div>
您templateHTML变量将包含'<b>Hi</b> there!'
第一种是细跟的ID template
元素,与ID grid
这是另一种元素中使用ID为model
变量的父元素。
设置模式test
model = "test"
结果在此:
<div id="test">
<div id="grid">
<div id="template"> <--- this element is found
</div>
</div>
</div>
这暗示着在你的HTML相同的ID,这不是一个好主意,因为不止一个元素它会经常混淆选择器。 (我相当肯定它也是无效的HTML)
第二种方法是在第一个选择器中找到的模板元素中简单地找到ID为templateBody
的元素。
让我们假设model
包含字符串"model"
。以下选择:
$("#" + model + " #grid #template")
找到与ID = template
和包含其本身包含在与ID = model
的元件内的ID的元素= grid
内的元件。选择:
$("#templatebody", template)
找到与ID的元素= templatebody
(的克隆)的内部先前匹配元件。
尽管如此,第一个选择器可以写成$("#template")
,因为ID应该是唯一的。如果情况并非如此,那么你会得到意想不到的结果。此外,以引入重复ID的方式克隆元素是一个坏主意。
var template = $("#" + model + " #grid #template")
会选择带有网格和模板的id以及模型变量的id。要找出这是什么,你可以提醒(模型)哪个显示值。
然后,您选择包含在您之前定义的模板变量中的templatebody元素。
的第一行中找到与ID #template的元件的#grid其内#” +模型内
ID被认为是在页面上唯一的,并且所述第一线理想地应被替换:
var template = $("#template").clone();
template.attr("id", "newid"); // assign a new unique id
代码是等价的,找到相同的元素的意识,写作
var template = $("#" + model).find("#grid).find("#template").clone(),
templateHtml = template.find("#templatebody").html();
但是如果HTML是有效的,那么这里只有将是一个与ID #template在这种情况下,代码可以简化为
var template = $("#template").clone();
template.find("#templateBody");
除了不考父/子模板和网格以及网格和模型之间的关系。如果需要的话,不能使用简化版本