首页 > 解决方案 > 未捕获的类型错误:$(...).makeRed 不是函数

问题描述

我想用 jquery 选择器调用自定义 javascript 函数,但这说 Uncaught TypeError: $(...).makeRed is not a function

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<h3 id="ch">Hello Wrld</h3>

</body>
</html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

<script>
    $(document).ready(function(){
        $.fn.makeRed = function(){
            this.html('welcome to all');
            return this;
    }
});
    $('#ch').makeRed();


</script>

标签: javascriptjqueryjquery-uiexceptionclient-side

解决方案


在准备就绪状态创建之前,您正在调用 makeRed。把它放在});这里是固定的代码段。:)

    $(document).ready(function(){
        $.fn.makeRed = function(){
            this.html('welcome to all');
            return this;
    }
     $('#ch').makeRed();
});
   
<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<h3 id="ch">Hello Wrld</h3>

</body>
</html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>


推荐阅读