.prepend不是一个函数 [英] .prepend is not a function

查看:380
本文介绍了.prepend不是一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下示例代码:

 <!DOCTYPE html> 
< html>
< head>
< script src =https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js>< / script>
< script>
$(document).ready(function(){
$(#btn1)。click(function(){
var btn = document.createElement(BUTTON);
btn.prepend(< b>前置文本< / b> ;.);
});
});
< / script>
< / head>
< body>
< p>这是一段。< / p>
< button id =btn1>预定文字< /按钮>
< / body>
< / html>

上面的代码会在控制台中引发错误:


btn.prepend不是函数

为什么会发生此错误?请提出解决方案。谢谢

请,请不要遵循W3School的低质量文章。对于您的解决方案:

  • btn 不是jQuery对象。它是一个JavaScript HTMLElement

  • .prepend()函数是一个jQuery函数。


    您的代码现在应该是:

      $(document).ready(function(){
    $(#btn1)。click(function(){
    var btn = $(this);
    btn.prepend(< b>前置文字< / b> ;.);
    });
    });

    工作片段



     

     < script src =https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js>< / script>< p>这是< / p>< button id =btn1>预定文字< / button>  



    请参阅上面的工作片段。点击运行代码片段并点击里面的按钮。


    Please consider the following sample code:

    <!DOCTYPE html>
    <html>
        <head>
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
            <script>
                $(document).ready(function(){
                    $("#btn1").click(function(){
                        var btn = document.createElement("BUTTON");     
                        btn.prepend("<b>Prepended text</b>. ");
                    });
                });
            </script>
        </head>
        <body>
            <p>This is a paragraph.</p>
            <button id="btn1">Prepend text</button>
        </body>
    </html>
    

    The above code throws the error in console like:

    btn.prepend is not a function

    Why does this error occur? Please suggest a solution. Thank You

    解决方案

    Please, kindly do not follow the low quality articles from W3Schools. For your solution:

    • The btn is not a jQuery object. It is a JavaScript HTMLElement.
    • The .prepend() function is a jQuery function.

    Your code now should be:

    $(document).ready(function(){
      $("#btn1").click(function(){
        var btn = $(this);
        btn.prepend("<b>Prepended text</b>. ");
      });
    });
    

    Working Snippet

    $(document).ready(function(){
      $("#btn1").click(function(){
        var btn = $(this);
        btn.prepend("<b>Prepended text</b>. ");
      });
    });

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <p>This is a paragraph.</p>
    <button id="btn1">Prepend text</button>

    See the working snippet above. Click on the Run Code Snippet and click the button inside.

    这篇关于.prepend不是一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆