alonli 发表于 2015-9-27 08:16:59

Sharepoint学习笔记—ECMAScript对象模型系列-- 7、获取和修改List的Lookup字段

  在前面我们提到了如何使用ECMAscript对象模型来操作普通的List Items,但如果我们操作的List包含有Lookup字段,那么我们又该怎么做呢?
首先参考此文搭建我们本文的测试环境
Sharepoint学习笔记---SPList--创建一个带有Lookup字段的List
  一、对于获取操作,我们使用如下代码


<script type="text/javascript">
    function GetLookupValue() {
      var context = new SP.ClientContext.get_current();
      var web = context.get_web();
      var list = web.get_lists().getByTitle('TestSale');
      var query = SP.CamlQuery.createAllItemsQuery();
      allItems = list.getItems(query);
      context.load(allItems, 'Include(ProductName,LookupStaffName)');
      context.executeQueryAsync(Function.createDelegate(this, this.successGetLookupValue),
                           Function.createDelegate(this, this.failedGetLookupValue));
    }
    function successGetLookupValue() {
      var TextFiled = "";
      var ListEnumerator = this.allItems.getEnumerator();
      while (ListEnumerator.moveNext()) {
            var currentItem = ListEnumerator.get_current();
            TextFiled += currentItem.get_item('ProductName') + '-' + currentItem.get_item('LookupStaffName').get_lookupValue() + '\n';
      }
      alert(TextFiled);
    }
    function failedGetLookupValue(sender, args) {
      alert("failed. Message:" + args.get_message());
    }
</script>  效果如下:

  二、对于修改操作,我们使用如下代码


<script type="text/javascript">
    function SetLookupValue() {
      var context = new SP.ClientContext.get_current();
      var web = context.get_web();
      var list = web.get_lists().getByTitle('TestSale');
      var query = SP.CamlQuery.createAllItemsQuery();
      allItems = list.getItems(query);
      context.load(allItems, 'Include(ProductName,LookupStaffName)');
      context.executeQueryAsync(Function.createDelegate(this, this.successSetLookupValue), Function.createDelegate(this, this.failedSetLookupValue));
    }
    function successSetLookupValue() {
      var TextFiled = ""
      var ListEnumerator = this.allItems.getEnumerator();
      while (ListEnumerator.moveNext()) {
            var currentItem = ListEnumerator.get_current();
            var newLookupField = new SP.FieldLookupValue();
            
            newLookupField.set_lookupId(2)//Updated with some lookup value for LookupStaffName column
                                          // Here is an id of your lookup list item 'Steve';
            currentItem.set_item('LookupStaffName', newLookupField);
            currentItem.update();
            // Call context.executeQueryAsync again
      }
    }
    function failedSetLookupValue(sender, args) {
      alert("failed. Message:" + args.get_message());
    }
</script>  效果如下:

  
  需要说明的是,在修改中,我们使用到代码


newLookupField.set_lookupID(2)  此代码中参数的含意就是从LookupItem所绑定的数据源List中去取值,如下图:
  
页: [1]
查看完整版本: Sharepoint学习笔记—ECMAScript对象模型系列-- 7、获取和修改List的Lookup字段