我正在使用SP枚举所有术语。分类.js SharePoint中的JSOM.在枚举时,我想检查当前术语是否有子项。我需要一些财产来检查,比如孩子计数。我怎样才能在最少的往返服务器的情况下做到这一点。我正在使用以下代码获取分类法,它工作正常。
请帮忙
$(document).ready(function () {
ExecuteOrDelayUntilScriptLoaded(function () {
SP.SOD.registerSod('sp.taxonomy.js', "/_layouts/15/sp.taxonomy.js");
`SP.SOD.executeFunc('sp.taxonomy.js', false, Function.createDelegate(this,`
function () {
var context = SP.ClientContext.get_current();
var taxonomySession = SP.Taxonomy.TaxonomySession.getTaxonomySession(context);
var termStore = taxonomySession.get_termStores().getByName("Taxonomy_qeFlDdEX32yZ3Q7EpEIeMQ==");
var termSet = termStore.getTermSet("ed6d3beb-6a49-4444-bc5d-456f747e139d");
var terms = termSet.getAllTerms();
context.load(terms);
context.executeQueryAsync(Function.createDelegate(this, function (sender, args) {
var termsEnumerator = terms.getEnumerator();
var menuItems = new Array();
while (termsEnumerator.moveNext()) {
var currentTerm = termsEnumerator.get_current();
var targetGroups = document.getElementById("selectTaxonomy");
var taxoGroup = document.createElement("option");
taxoGroup.text = currentTerm.get_name();
targetGroups.add(taxoGroup);
}
}), Function.createDelegate(this, function (sender, args) {
alert('The error has occured: ' + args.get_message());
}));
}));
},"sp.js")
});
您可以使用 SP。属性,用于获取子术语对象的数量,例如:
var termSetId = '--guid goes here--';
getTerms(termSetId,
function(terms){
for(var i = 0;i < terms.get_count();i++){
var term = terms.get_item(i);
var hasChildTerms = (term.get_termsCount() > 0);
//...
}
},
function(sender,args)
{
console.log(args.get_message());
});
哪里
function getTerms(termSetId,success,error) {
var context = SP.ClientContext.get_current();
var taxSession = SP.Taxonomy.TaxonomySession.getTaxonomySession(context);
var termStore = taxSession.getDefaultSiteCollectionTermStore();
var termSet = termStore.getTermSet(termSetId);
var terms = termSet.getAllTerms();
context.load(terms);
context.executeQueryAsync(function () {
success(terms)
},
error);
}
一些建议
1)首选SP.SOD.loadMultiple
函数来加载多个库,例如
SP.SOD.registerSod('SP.ClientContext', SP.Utilities.Utility.getLayoutsPageUrl('sp.js'));
SP.SOD.registerSod('SP.Taxonomy.TaxonomySession', SP.Utilities.Utility.getLayoutsPageUrl('sp.taxonomy.js'));
SP.SOD.loadMultiple(['SP.ClientContext', 'SP.Taxonomy.TaxonomySession'], function(){
//your code goes here
});
2) 避免任何硬编码,例如:
/_layouts/15/sp.taxonomy.js -> SP.Utilities.Utility.getLayoutsPageUrl('sp.taxonomy.js')
替换该行:
var termStore = taxonomySession.get_termStores().getByName("Taxonomy_qeFlDdEX32yZ3Q7EpEIeMQ==");
有了这个:
var termStore = taxonomySession.getDefaultSiteCollectionTermStore();
- 在大多数情况下可以避免使用Function.createDelegate函数