简体   繁体   English

自定义函数的jQuery Uncaught TypeError

[英]Jquery Uncaught TypeError on Custom function

In my code I am getting Uncaught TypeError: Cannot read property '1' of null in console but my function looks fine I don't know why its causing this error every time how ever other functions like this I prepared works totally fine Here is working jsFiddle 在我的代码中,我遇到了Uncaught TypeError:无法console 读取null的属性“ 1”,但是我的函数看起来不错,我不知道为什么每次我准备的其他函数都正常时,它都会导致此错误的原因jsFiddle

Here is the part of my code 这是我的代码的一部分

$(document).ready(function() {
    var URLCheck = document.referrer;
    var frameLocation = URLCheck.match(/:\/\/(.[^/]+)/)[1];
    var whiteLocation = 'mywebsite.com';
    if (whiteLocation == frameLocation) {
        $('#adprimary').remove();
    }
});

Because String.prototype.match returns null if no match was found and you're trying to access the attribute 1 of null . 由于String.prototype.match返回null ,如果没有匹配的发现和你试图访问属性1null

Check if it's null before accessing any attributes: 在访问任何属性之前检查它是否为null

var frameLocation = URLCheck.match(/:\/\/(.[^/]+)/);
if(frameLocation !== null) {
  frameLocation = frameLocation[1];
}

Or the short version: 或简称:

var frameLocation = (URLCheck.match(/:\/\/(.[^/]+)/) || [])[1];

Inside your code: 在您的代码内:

$(document).ready(function() {
    var URLCheck = document.referrer || ''; // make sure referrer is a string
    var frameLocation = URLCheck.match(/:\/\/(.[^/]+)/)[1];
    if(frameLocation !== null) {
      frameLocation = frameLocation[1];
    }
    var whiteLocation = 'mywebsite.com';
    if (whiteLocation == frameLocation) {
        $('#adprimary').remove();
    }
});
  1. the document.referrer may not exists; document.referrer可能不存在;
  2. the URLCheck.match(/:\\/\\/(.[^/]+)/) may be undefined URLCheck.match(/:\\/\\/(.[^/]+)/)可能未定义

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM