jQuery Get TypeError:a为null,带代码

时间:2016-06-17 09:55:53

标签: javascript jquery

我正在使用jQuery 2.2.4和一个小脚本,脚本让jQuery给我以下错误:

TypeError: a is null


...th>0},fa.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},fa....

控制台指向" a.ownerDocument"

现在这是导致错误发生的代码:

$(function() {
        $('[class*="inc:"]').each(function() {
            var match = /inc:(\S+)/.exec(this.className || '');
            match && $(this).inc(unescape(match[1]));
        });
    });

我的index.html代码是:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <title></title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script> 
  <script type="text/javascript" src="inc.js"></script>

</head>
<body>

    <p class="inc:footer.html">This text will be replaced
    with footer.html</p>


</body>
</html>

这是完整的inc.js:

(function($) {
    $.fn.inc = function(url, transform, post, t) {
        return this.length && url ? this.each(function() {
            t = $(this);
            $.ajax({
                url: url,
                success: function(txt, jqXHR, textStatus) {
                    t.html($.isFunction(transform) ? transform(txt, url) : txt);
                    $.isFunction(post) && post(url, jqXHR, textStatus);
                }
            });
        }) : this;
    };

    $(function() {
        $('[class*="inc:"]').each(function() {
            var match = /inc:(\S+)/.exec(this.className || '');
            match && $(this).inc(unescape(match[1]));
        });
    });

})(jQuery);

如何解决此问题?

1 个答案:

答案 0 :(得分:2)

改为使用

  $(function() {
    $('[class*="inc:"]').each(function() {
        var match = /inc:(\S+)/.exec(this.className || '');
        if(typeOf(match[1]) != "undefined")
          match && $(this).inc(unescape(match[1]));
    });
  });