无法解决“标题”尚未初始化

问题描述 投票:0回答:1

我正在尝试禁用用户删除与当前记录关联的任何附件的能力,这些附件处于编辑模式。我在Sharing to the Point上找到了此代码。为了运行它,我不得不进行一些更改。我认为我的问题是我的从属脚本未正确加载,因此该函数出错了。代码是:

//if (document.referrer == "" || document.referrer == null) 
if (window.location.pathname.toLowerCase().indexOf("editform.aspx") > -1) {
   // These two lines are required, without it my code won't run.
   SP.SOD.executeFunc('SP.js', 'SP.ClientContext');
   SP.SOD.executeFunc('sp.runtime.js');

   var listName = "BSMRequests"; 
   var currentItemID;
   var attachmentAuthor = [];
   var itemArray = [];

   $(document).ready(function(){  
      // Get ID of the current item.
      currentItemID = window.location.href.toLowerCase();
      currentItemID = currentItemID.substring(currentItemID.toLowerCase().indexOf("?id=") + 4,currentItemID.toLowerCase().indexOf("&source="));
      // Remove the line below in case the URL of your item is 
      // not shown as a modal dialog.
      //currentItemID = currentItemID.substring(0, currentItemID.toLowerCase().indexOf("&isdlg"));
      //console.log('currentItemID='+currentItemID);

      // Save the ID of the current item in the session 
      // (not necessary, but I prefer it this way)
      sessionStorage.setItem("SessionItemCurrentItemID", currentItemID);

      // Get attachments of current item.
      var url = "/_api/Web/Lists/getByTitle('" + listName + "')/Items(" + currentItemID + ")/AttachmentFiles",
         qs = "?$select=ID,Author/Title,*&$expand=Author,AttachmentFiles",
         siteUrl = "https://share.health.wisconsin.gov/hc/teams/MES";
      $.ajax( {
         url : siteUrl + url + qs,
         type : 'GET',
         headers : {
            'accept' : 'application/json;odata=verbose',
            'content-type' : 'application/json;odata=verbose'
         },
         success : successHandler,
         fail : failHandler
      });  

      function successHandler(data) {
         if (data) {
         // If the item has attachments, then run this function.
               //console.log('yes? attachments');
            $.each(data.d.results, function() {
               //console.log('processing results');
               getWebProperties(sessionStorage.getItem("SessionItemCurrentItemID"));
            });
         } //else {console.log('No attachments');}
      }

      function failHandler(data, errCode, errMessage) { 
         console.log('Error: ' + errMessage); 
      }

      function getWebProperties(itemID) {
         var attachmentFiles;
         var ctx = new SP.ClientContext.get_current();
         var web = ctx.get_web();
         var attachmentFolder = web.getFolderByServerRelativeUrl('Lists/'+listName+'/Attachments/' + itemID);
         attachmentFiles = attachmentFolder.get_files();
         ctx.load(attachmentFiles);
         ctx.executeQueryAsync(function(){
            // I can't remember what the $2_1 was again, but anyway...
            for (var j = 0; j < attachmentFiles["$2_1"].length; j++) {
               var author = attachmentFiles.itemAt(j).get_author(); 
               attachmentAuthor.push([attachmentFiles.itemAt(j).get_name(),author]);

               // You'll need to load the author along with the title parameter,
               // in order to be able to fetch the name of the author later.
               ctx.load(author, 'Title');
               ctx.executeQueryAsync(function(){}, function(err) {});
            }
            // Loop is not necesarrily required, but you will need to set a
            // timeout. Comes in handy when you have a lot of attachments.
            checkAttachmentsLoop();
         }, function(err) {});
      }

      function checkAttachmentsLoop() {
         setTimeout(function(){
            if (attachmentAuthor.length) {
               checkAttachments();
            }
            else {
               checkAttachmentsLoop();
            }
         },100);
      }

      function checkAttachments() {
         for (var h = 0; h < attachmentAuthor.length; h++) {
            // if you log attachmentAuthor[h][0] to the concole, you'll get 
            // the name of the attachment.
            // if you log attachmentAuthor[h][1].get_title() to the console,
            // you'll get the name of the author.

            var currentAuthor = attachmentAuthor[h][1].get_title();
            // If the current user is not the author of the current attachment,
            // then we disable the ability to delete the attachment from the item.
            // var currentUser = "Harvancik, Steve Skkk";
            var currentUser = sessionStorage.getItem("sessionItemUserName");
            if (currentAuthor != currentUser) {
               var tr = document.getElementById("idAttachmentsTable").getElementsByTagName("tr");
               for (var i = 0; i < tr.length; i++) {
                  var currentTR = $(tr)[i];
                  var anchors = $(currentTR).find("a")[0];
                  var deletes = $(currentTR).find("a")[1];
                  if (anchors.innerHTML == attachmentAuthor[h][0]) {
                     $(currentTR).attr("disabled", "disabled");
                     $(anchors).css("color", "#b1b1b1");
                     $(anchors).removeAttr("href");
                     $(anchors).removeAttr("onclick");
                     $(deletes).css("text-decoration", "line-through");
                     $(deletes).css("color", "#b1b1b1");
                     $(deletes).removeAttr("href");
                     $(deletes).removeAttr("onclick");
                  }
               }
            }
         }
      }
   })
}
else {
   if (sessionStorage.getItem("SessionItemCurrentItemID") != null) {
      sessionStorage.removeItem("SessionItemCurrentItemID");
   }
}

我得到的错误属于以下类型:

Uncaught Error: The property or field 'Title' has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested.

我首先尝试将其放入函数中,并通过ExecuteOrDelayUntilScriptLoaded进行调用,但这没有用。调用此函数并在运行之前加载相关脚本的最佳方法是什么?

谢谢

javascript sharepoint-2013
1个回答
0
投票

authorattachmentAuthor之前推到ctx.executeQueryAsync,因此尚未加载该值,您可以在checkAttachments中加载它。

测试脚本:

 <script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script type="text/javascript">
        //if (document.referrer == "" || document.referrer == null)
        if (window.location.pathname.toLowerCase().indexOf("editform.aspx") > -1) {
            // These two lines are required, without it my code won't run.
            SP.SOD.executeFunc('SP.js', 'SP.ClientContext');
            SP.SOD.executeFunc('sp.runtime.js');

            var listName = "MyList";
            var currentItemID;
            var attachmentAuthor = [];
            var itemArray = [];

            $(document).ready(function () {
                // Get ID of the current item.
                currentItemID = window.location.href.toLowerCase();
                currentItemID = currentItemID.substring(currentItemID.toLowerCase().indexOf("?id=") + 4, currentItemID.toLowerCase().indexOf("&source="));
                // Remove the line below in case the URL of your item is
                // not shown as a modal dialog.
                //currentItemID = currentItemID.substring(0, currentItemID.toLowerCase().indexOf("&isdlg"));
                //console.log('currentItemID='+currentItemID);

                // Save the ID of the current item in the session
                // (not necessary, but I prefer it this way)
                sessionStorage.setItem("SessionItemCurrentItemID", currentItemID);

                // Get attachments of current item.
                var url = "/_api/Web/Lists/getByTitle('" + listName + "')/Items(" + currentItemID + ")/AttachmentFiles",
                    qs = "?$select=ID,Author/Title,*&$expand=Author,AttachmentFiles",
                    siteUrl = _spPageContextInfo.webAbsoluteUrl;
                $.ajax({
                    url: siteUrl + url + qs,
                    type: 'GET',
                    headers: {
                        'accept': 'application/json;odata=verbose',
                        'content-type': 'application/json;odata=verbose'
                    },
                    success: successHandler,
                    fail: failHandler
                });

                function successHandler(data) {
                    if (data) {
                        // If the item has attachments, then run this function.
                        //console.log('yes? attachments');
                        $.each(data.d.results, function () {
                            //console.log('processing results');
                            getWebProperties(sessionStorage.getItem("SessionItemCurrentItemID"));
                        });
                    } //else {console.log('No attachments');}
                }

                function failHandler(data, errCode, errMessage) {
                    console.log('Error: ' + errMessage);
                }

                function getWebProperties(itemID) {
                    var attachmentFiles;
                    var ctx = new SP.ClientContext.get_current();
                    var web = ctx.get_web();
                    var attachmentFolder = web.getFolderByServerRelativeUrl('Lists/' + listName + '/Attachments/' + itemID);
                    attachmentFiles = attachmentFolder.get_files();
                    ctx.load(attachmentFiles);
                    ctx.executeQueryAsync(function () {
                        // I can't remember what the $2_1 was again, but anyway...
                        for (var j = 0; j < attachmentFiles["$2_1"].length; j++) {
                            var author = attachmentFiles.itemAt(j).get_author();
                            attachmentAuthor.push([attachmentFiles.itemAt(j).get_name(), author]);                            
                        }
                        // Loop is not necesarrily required, but you will need to set a
                        // timeout. Comes in handy when you have a lot of attachments.
                        checkAttachmentsLoop();
                    }, function (err) { });
                }

                function checkAttachmentsLoop() {
                    setTimeout(function () {
                        if (attachmentAuthor.length) {
                            checkAttachments();
                        }
                        else {
                            checkAttachmentsLoop();
                        }
                    }, 100);
                }

                function checkAttachments() {
                    var ctx = new SP.ClientContext.get_current();
                    for (var h = 0; h < attachmentAuthor.length; h++) {
                        // if you log attachmentAuthor[h][0] to the concole, you'll get
                        // the name of the attachment.
                        // if you log attachmentAuthor[h][1].get_title() to the console,
                        // you'll get the name of the author.

                        // You'll need to load the author along with the title parameter,
                        // in order to be able to fetch the name of the author later.
                        ctx.load(attachmentAuthor[h][1], 'Title');
                        ctx.executeQueryAsync(function () {
                            var currentAuthor = attachmentAuthor[h][1].get_title();
                            console.log(currentAuthor);
                        }, function (err) {
                            console.log(err);
                        });
                        //var currentAuthor = attachmentAuthor[h][1].get_title();
                        // If the current user is not the author of the current attachment,
                        // then we disable the ability to delete the attachment from the item.
                        // var currentUser = "Harvancik, Steve Skkk";
                        var currentUser = sessionStorage.getItem("sessionItemUserName");
                        if (currentAuthor != currentUser) {
                            var tr = document.getElementById("idAttachmentsTable").getElementsByTagName("tr");
                            for (var i = 0; i < tr.length; i++) {
                                var currentTR = $(tr)[i];
                                var anchors = $(currentTR).find("a")[0];
                                var deletes = $(currentTR).find("a")[1];
                                if (anchors.innerHTML == attachmentAuthor[h][0]) {
                                    $(currentTR).attr("disabled", "disabled");
                                    $(anchors).css("color", "#b1b1b1");
                                    $(anchors).removeAttr("href");
                                    $(anchors).removeAttr("onclick");
                                    $(deletes).css("text-decoration", "line-through");
                                    $(deletes).css("color", "#b1b1b1");
                                    $(deletes).removeAttr("href");
                                    $(deletes).removeAttr("onclick");
                                }
                            }
                        }
                    }
                }
            })
        }
        else {
            if (sessionStorage.getItem("SessionItemCurrentItemID") != null) {
                sessionStorage.removeItem("SessionItemCurrentItemID");
            }
        }
    </script>

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.