2011-01-31 43 views
0

您好我有一些JSP標記內生成的代碼,它使用jQuery數據函數關聯數據與div。重構代碼來刪除uuid

我已經使用UUID將jQuery腳本鏈接到頁面上的div。 但是,這種方法很醜,不方便,我想知道是否有方法來重構它不需要UUID。

代碼如下所示。

for(DomainObject domainObject : domainObjects){ 
//... 
     String uuid = UUID.randomUUID().toString(); 

     out.println("<div id='" +uuid + "' class='" + divClass + "'>"); 

     // Write out the details of this domain object. 
     out.println(/*...*/); 

     // Associate data with the div 
     out.println("<script type='text/javascript'>$('#"+uuid+"').data('domainObject'," + jsonSerializer.exclude("class").serialize(domainObject) + ")</script>"); 
     out.println("</div>"); 
//... 
    } 
+0

你需要在你的js中完整的域對象嗎? – 2011-01-31 11:33:35

回答

1

兩種方式(實施例使用JSTL/EL)

  1. 域對象的使用ID代替,如果有的話。

    <div id="do_${domainObject.id}"> 
    ... 
    <script>$('#do_${domainObject.id}').foo();</script> 
    
  2. 使用循環計數器。

    <c:forEach items="${domainObjects}" var="domainObject" varStatus="loop"> 
        <div id="do_${loop.index}"> 
        ... 
        <script>$('#do_${loop.index}').foo();</script> 
    </c:forEach> 
    

注意,ID 必須開始以字母字符。 ID以數字開頭是非法的。 UUID可能會以數字開頭返回ID。

+0

啊對,我完全錯過了。是的你是對的,他們中的一些人確實以一個數字開頭 – 2011-01-31 20:35:37

0

不知道這是什麼醜陋的。也許你只是想要一個較短的ID?

UUID是唯一的通用。這遠遠超過了HTML頁面中元素ID的要求 - 它們在頁面中是唯一的。

創建長度爲1或2位的頁面唯一ID是很簡單和合適的。您的JSP需要用randomPageId()替換randomUUID(),它會返回一系列的d1,d2,d3或其他。

3

如果你能夠使用jQuery 1.4.3,有一種非常簡單的方法可以將數據關聯到dom中的元素。由於1.4.3 jQuery將檢查是否有任何data attributes元素,並自動將它們提供通過。數據(「鑰匙」)

<div class='myClass' data-domainObject='{"Name": "I am in your data!"}'> 
    Domain Object 
</div> 

$(function(){ 
    alert($(".myClass").data("domainObject").Name); 
}); 

例如在jsfiddle

由於看來你只是用腳本標籤要添加數據元素這個選項可能是合適的,看起來像這樣(注意我沒有jsp的經驗):

for(DomainObject domainObject : domainObjects){ 
//... 

     out.println("<div class='" + divClass + "' data-domainObject='" + jsonSerializer.exclude("class").serialize(domainObject)+ "'>"); 

     // Write out the details of this domain object. 
     out.println(/*...*/); 
     out.println("</div>"); 
//... 
    } 
+0

啊是的,我之前看到過這個選項。我不確定這是否是一個好主意,因爲直到HTML5纔有效。我想這真的沒關係,我可以試試看。 – 2011-01-31 20:43:04