2015-10-26 81 views
-1

我使用把手。我註冊了一個調用函數的助手。把手方法調用不返回值

Handlebars.registerHelper("getContactCategoryById", getContactCategoryById); 

功能

function getContactCategoryById(categoryId) { 
    var category = sessionStorage.getItem("category"); 

    $.each(jQuery.parseJSON(category), function() { 
     if (this.contactCategoryId == categoryId) { 
      return this.name; 
     } 
    }); 
} 

在我的模板,我的函數被調用,當我調試,getContactCategoryById返回一個值,但它從來沒有在表中顯示。 我可以看到當我看到html代碼,然後contact-category-id爲data-contact-category-id標籤賦值。

<script id="lodger-contact-available-result-template" type="text/x-handlebars-template"> 
    <table id="lodgerContactAvailableTableResult" style="min-height:200" data-show-header="true" class="table table-striped" data-toggle="table" data-height="330"> 
    <thead> 
    <tr> 
    <th>Category</th> 
    </tr> 
    </thead> 
    <tbody> 
    {{#each this}} 
    <tr> 
    <td data-contact-category-id={{contactCategoryId}}>{{getContactCategoryById contactCategoryId}}</td> 
    </tr> 
    {{/each}} 
    </tbody> 
    </table 

</script> 

編輯:解決方案,需要做一個回報存在的每一個,並獲得價值

function getContactCategoryById(categoryId) { 
    var category = sessionStorage.getItem("category"); 
    var toReturn; 

    $.each(jQuery.parseJSON(category), function() { 
     console.log(this.contactCategoryId, categoryId); 
     if (this.contactCategoryId == categoryId) { 
      toReturn = this.name; 
      return false; 
     } 
    }); 

    return toReturn; 
} 
+0

你加的console.log線,看看是怎麼回事上?如果沒有匹配,你也不會返回任何東西。 – epascarello

+0

如果我把getContactCategoryById中的console.log,我可以看到值。如果找不到價值,我不想要任何價值。 –

+0

'的console.log(this.contactCategoryId,的categoryId);' – epascarello

回答

2

的問題是,您是從jQuery.each返回它本身就是一個功能等你回來值被吞噬jQuery.each,並且您的幫助函數getContactCategoryById最終不會返回任何內容(或始終準確地返回undefined)。

你需要做的是停止循環,一旦你找到你所需要的東西,然後回到你發現了什麼循環完成後:

function getContactCategoryById(categoryId) { 
    var category = sessionStorage.getItem("category"); 
    var foundName = ''; 
    $.each(jQuery.parseJSON(category), function() { 
     if (this.contactCategoryId == categoryId) { 
      foundName = this.name; 
      return false; // returning false in jQuery.each stops the iteration 
     } 
    }); 
    return foundName; // return the name you found 
} 
+0

感謝,它的溶液中的發現在幾分鐘前。 –