Uncaught TypeError: Cannot set property 'inner

2019-04-16 20:11发布

问题:

I am making a barcode scanning app using phonegap-1.4.1 for android. I need to define a n array code[] which can store all the barcode text scanned and i need to define a variable k which act as a counter which get incremented by 1 after every scan so that I can store detail in code[k]. So here is my previous javascript file where i have defined an array and an variable counter.

     localStorage["counter"]=0;
     var code = new Array(100);
     localStorage.setItem("code", JSON.stringify(code));

and here is my another js file where i am calling the stored array and printing the value stored in that array as "id". myvalue1 is the barcode text obtained from the scan.

   var barcodeVal = localStorage.getItem("myvalue1");
   var test2 = localStorage.getItem("code");
   code = JSON.parse(test2);
   var k = parseInt(localStorage.getItem("counter"));
   code[k] = "code[k]";
   document.getElementById(code[k]).innerHTML = barcodeVal;
   k = k + 1;
   localStorage["counter"]=k;
   localStorage.setItem("code", JSON.stringify(code));

I am calling the barcode scan function again and again. Thats why I am using an array for storing the data of the Barcode scanned.Here is my scan js file as well which gives the value of myvalue1

 <script type="text/javascript">
  var scanCode = function () {
      window.plugins.barcodeScanner.scan(
          function (result) {

               alert("Scanned Code: " + result.text + ". Format: " + result.format + ". Cancelled: " + result.cancelled);
              localStorage.setItem("myvalue1", result.text);
              window.location.href = 'page5.html';

          }, function (error) {
              alert("Scan failed: " + error);
       });
  }

I am getting the error as Uncaught TypeError: Cannot set property 'innerHTML' of null. I am new to phonegap and coding . Anyone please help me out with the issue. Thanks in advance.

回答1:

You don't need to keep track of variable k. You simple manage your all barcode values using below script.

Please check below jsFiddle...Run it twice you can see difference.

JSFiddle

<script>
function SaveDataToLocalStorage(barcodeValue)
{

    var oldItems = JSON.parse(localStorage.getItem('barcodes')) || [];
    var newItem = {
        'barcode': barcodeValue
    };
    oldItems.push(newItem);
    localStorage.setItem('barcodes', JSON.stringify(oldItems));

}
SaveDataToLocalStorage("123456879FFGG");
</script>