請參閱下面的代碼以下問題描述:修改現有的代碼,以接受多個參數
// Populate a select list with pt codes.
this.populateCodeList = function (ptName_, listSelector_) {
if (!ptName_) { return self.displayError("Invalid pt name", "populatecodeList"); }
if (!listSelector_) { return self.displayError("Invalid list selector", "populatecodeList"); }
var pt = self.registry.pt[ptName_];
if (!pt) { return self.displayError("Invalid PT: " + ptName_, "populateCodeList"); }
var html = "";
$_.each(pt.codes, function (index_, code) {
if (!code || !code.id || !code.name) { return self.displayError("Invalid code at index " + index_, "populateCodeList"); }
html += "<option value='" + code.id + "'>" + code.name + "</option>";
});
$_(listSelector_).html(html);
};
問題描述:
我打電話就像在我的代碼如下上述功能:
app_.populateCodeList("First Attribute", self.selectors.add_attribute_dialog + " .attribute-name");
一切工作正常。然而,當我嘗試調用上述函數這樣具有第二屬性由逗號分隔 如下:
app_.populateCodeList("First Attribute,Second Attribute", self.selectors.add_attribute_dialog + " .attribute-name");
我得到以下錯誤Invalid PT:First Attribute,Second Attribute in populateCodeList
這是這條線在上面的代碼if (!pt) { return self.displayError("Invalid PT: " + ptName_, "populateCodeList"); }
所以基本上我的代碼沒有被編程以處理由逗號但單可變分開的兩個參數,其在線所示
var pt = self.registry.pt[ptName_];
如何確保上面的行在需要時接受單參數和雙參數?
謝謝
感謝。雖然,我沒有看到任何錯誤,而像這樣調用它'app_.populateCodeList(「第一個屬性,第二個屬性」,self.selectors.add_attribute_dialog +「.attribute-name」); '在使用您的更改後,我看到的信息僅與「First Attribute」參數相關。如果我這樣做'app_.populateCodeList(「Second Attribute,First Attribute」,self.selectors.add_attribute_dialog +「.attribute-name」); '我只看到與第二個屬性相關的信息,而不是兩者。你知道爲什麼它只拾取第一個參數,而不是兩個? – Tan
我的不好,更新了代碼。我需要在循環的外部移動'$ _(listSelector _)。html(html);否則最後一次迭代將使用上一次迭代中生成的html來重新生成所有的html。 –
謝謝。只要我把它移到循環之外,就會在瀏覽器控制檯中出現'Uncaught ReferenceError:html is not defined'錯誤。 – Tan