.prepend is not a function

梦想的初衷 提交于 2019-12-02 14:43:08

问题


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


回答1:


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.




回答2:


The error appears because createElement() returns a DOMElement which does not have an append() method; that's only available on jQuery objects. You need to either wrap the DOMElement to a jQuery object or, better yet, create the element in jQuery:

$("#btn1").click(function(){
     var btn = $('<button />');     
     btn.prepend("<b>Prepended text</b>. ");
     // add the btn to the DOM somewhere...
});


来源:https://stackoverflow.com/questions/36059045/prepend-is-not-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!