2012-05-03 30 views
1

我不能做什麼這2行的意思是:這些Jquery選擇器是什麼意思?

var template = $("#" + model + " #grid #template").clone(); 
var templateHtml = $("#templatebody", template).html(); 

我無法理解的選擇這兒過得知道的clone()和HTML()做

回答

3
$("#" + model + " #grid #template") 

這是元素ID grid,內部和元件與在所述model變量中設置的內部id尋找具有的templateid的元件。

例如,如果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> 
1

第一,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!'

2

第一種是細跟的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的元素。

2

讓我們假設model包含字符串"model"。以下選擇:

$("#" + model + " #grid #template") 

找到與ID = template和包含其本身包含在與ID = model的元件內的ID的元素= grid內的元件。選擇:

$("#templatebody", template) 

找到與ID的元素= templatebody(的克隆)的內部先前匹配元件。

儘管如此,第一個選擇器可以寫成$("#template"),因爲ID應該是唯一的。如果情況並非如此,那麼你會得到意想不到的結果。此外,以引入重複ID的方式克隆元素是一個壞主意。

1
var template = $("#" + model + " #grid #template") 

會選擇帶有網格和模板的id以及模型變量的id。要找出這是什麼,你可以提醒(模型)哪個顯示值。

然後,您選擇包含在您之前定義的模板變量中的templatebody元素。

0

的第一行中找到與ID #template的元件的#grid其內#」 +模型內

ID被認爲是在頁面上唯一的,並且所述第一線理想地應被替換:

var template = $("#template").clone(); 
template.attr("id", "newid"); // assign a new unique id 
1

代碼是等價的,找到相同的元素的意識,寫作

var template = $("#" + model).find("#grid).find("#template").clone(), 
    templateHtml = template.find("#templatebody").html(); 
  • 發現w ^帽子everelement具有和ID等於模型的值,
  • 其中找到一個元素與ID網格
  • 內找到一個與模板的ID。
  • 克隆找到的元素搜索
  • 在克隆中,其中一個id爲templateBody。

但是如果HTML是有效的,那麼這裏只有將是一個與ID #template在這種情況下,代碼可以簡化爲

var template = $("#template").clone(); 
    template.find("#templateBody"); 

除了不考父/子模板和網格以及網格和模型之間的關係。如果需要的話,不能使用簡化版本