2012-07-20 51 views
0

在項目中,我所面臨的問題與類至極調用javascript代碼呈現
HTML中wicket.Suppose我們有一個類ExamplePanel與下面的代碼檢票口面板調用JavaScript或從檢票口面板類修改CSS

public final class ExamplePanel extends Panel { 

     public ExamplePanel(String id) { 
      super(id); 
      add(new Label("someText", "hello")); 
     }} 

和HTML文件 'ExamplePanel'

<html xmlns:wicket> 
    <head> 
     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> 
     <title>ExamplePanel</title> 
     <wicket:head> 
      <link href="panel.css" rel="stylesheet"/> 
      <script src="jquery.min.js"></script> 
      <script src="jquery-ui.min.js"></script> 

     </wicket:head> 
    </head> 
    <body> 
     <wicket:panel> 
      <div id="parentContainer"> 
       <div id="box" wicket:id="someText"></div> 
      </div> 
     </wicket:panel> 
    </body> 
</html> 

和下面的CSS

#box{ 
    background: #f0f0f0; 
    width: 50px; 
    height: 50px; 
    position: absolute; 
    top: 200px; 
    left: 200px; 
    font-size: 1.5em; 
    word-wrap: break-word; 
} 

#parentContainer{ 
    width:500px; 
    height: 500px; 
    background:RGB(57,51,51); 
    position:relative; 
} 

從這個代碼,我們有parentContainer格內框,我需要通過位置座標框,當初始化ExamplePanel類, 例如:

public ExamplePanel(String id) { 
    super(id); 
    add(new Label("someText", "hello")); 
    // add some code for css positioning of box div 
    // $('#div').css({position:'relative',top:'5px',left='29px'}) for example 
} 

有什麼建議?

回答

7

ExamplePanel必須實現IHeaderContributor它提供了一個方法renderHead(IHeaderResponse)。從這個方法中,你可以調用response.renderString()來傳遞你想要應用的樣式。在你的情況下,你不添加樣式,你添加一個JS調用,添加一些樣式。這樣做可以使Java調用稍微簡單,因爲不是需要創建爲您呈現字符串的一部分,你只需要調用response.renderJavascript()...

public class ExamplePanel implements IHeaderContributor { 
    public ExamplePanel(String id) { 
     super(id); 

     add(new Label("someText", "hello")); 
    } 

    @Override 
    public void renderHead(IHeaderResponse response) { 
     // use this if you want to add only the styles 
     response.renderString("<style>#div {position:'relative'; top:'5px'; left='29px';}</style>"); 

     // or, use this if you still want the JS selector 
     // the uniqueId should not be null if you want Wicket to check if the script has already been rendered 
     response.renderJavascript("$('#div').css({position:'relative',top:'5px',left='29px'})", null); 
    } 
} 

的IHeaderContributor界面旨在促進添加諸如JavaScript和CSS之類的資源。

+0

哇,這比我想象的容易!謝謝您的回答!還有一個問題:是否有任何解決方案可以從java類獲取javascript變量值? – 2012-07-21 02:34:31

+0

當然,在調用renderJavascript()之前,您只需要使用該變量創建String。在調用renderJavascript()之前,您可以使用StringBuffer來追加該腳本的各個部分。 – 2012-07-21 02:48:59

+0

不,我的意思是從java中的javascript變量中獲取值,例如在html文件中我們有並在我的ExamplePanel類中獲取x的值。 – 2012-07-21 03:26:19