2011-04-20 159 views
2

我使用的jQuery模板插件(jquery.tmpl.js)和大部分我理解它,但我真的很努力让它与元素的工作,其中的选项select元素来自一个JSON对象,但所选值来自另一个JSON对象的属性。下面是我的代码:jQuery.tmpl和<select>选项

的HTML:

 <fieldset id="userFieldset"> 
      <script id="userTemplate" type="text/x-jquery-tmpl"> 

        <label for="TitleId">Title</label> 
        <select value="${TitleId}" id="TitleId" name="TitleId"> 
         {{tmpl(titles) "#titleTemplate"}}        
        </select> 
        <label for="UserName">Name</label> 
        <input type="text" name="UserName" id="UserName" class="text ui-widget-content ui-corner-all" value="${UserName}"/> 
        <label for="Password">Password</label> 
        <input type="password" name="Password" id="Password" class="text ui-widget-content ui-corner-all" value="${Password}"/>    
      </script>  

      <script id="titleTemplate" type="text/x-jquery-tmpl"> 
       <option value="${ID}">${Value}</option> 
      </script>   
     </fieldset> 

的JavaScript:

var titles = Sys.Serialization.JavaScriptSerializer.deserialize("[{\"ID\":3,\"Value\":\"Mr\"}, {\"ID\":2,\"Value\":\"Ms\"}, {\"ID\":1,\"Value\":\"Doctor\"}]", false); 

function showEditUser(user) { 
    $("#userFieldset").empty();   
    $("#userTemplate").tmpl(user).appendTo("#userFieldset");  
    $("#userDialog").dialog("open");  
} 

然而,这并没有改变TitleId选择的设定值。任何帮助将不胜感激。

回答

4

您需要在选项元素上设置选定的属性。

这样做的一种方法是将选项传递给包含TitleId的{{tmpl}},以便您可以将它与标题对象的ID变量进行比较。

这看起来是这样的:

<fieldset id="userFieldset"> 
    <script id="userTemplate" type="text/x-jquery-tmpl"> 
     <select id="TitleId" name="TitleId"> 
      {{tmpl(titles, { selectedId: TitleId }) "#titleTemplate"}}        
     </select>   
    </script>  

    <script id="titleTemplate" type="text/x-jquery-tmpl"> 
     <option {{if ID === $item.selectedId}}selected="selected"{{/if}} value="${ID}">${Value}</option> 
    </script>   
</fieldset> 

所以,你传递TitleId你的孩子的模板,并调用它selectedId(你当然可以叫它TitleId太)。您可以在$item对象(如$item.selectedId)之外的子模板中访问它,并使用它来确定是否应在option元素上设置selected属性。

样品在这里:http://jsfiddle.net/rniemeyer/YCQ9S/

+0

打我吧。 :) – Kon 2011-04-20 14:08:04

1

“价值” 是不是<select> HTML标签的有效属性。您必须在<option>本身上设置“选定”属性才能使其处于选中状态。试试这样的:

<script id="titleTemplate" type="text/x-jquery-tmpl"> 
    <option value="${ID}" selected="${checkSelected(this.data.ID)}">${Value}</option> 
</script> 

<script> 
function checkSelected(id) 
{ 
    // logic to determine if this id should be the selected one. 
    return "selected"; //or not 
} 
</script> 
+0

我需要这种反向功能才能为一组已建成的选择列表构建模板。谢谢 – deltree 2013-10-10 13:35:36