简体   繁体   中英

How can i solve a "no method 'appendTo' error?

How can I solve this error:

Uncaught TypeError: Object has no method 'appendTo' in the following code :

    function refresh(){
        $('#contacts').empty();
        $( "#contactTmpl" ).tmpl( {contacts:contacts} ).appendTo( "#contacts" );
        $( ".contact" ).each( function(i) {
            var contact = contacts[i];
            $( "input.tomap", this ).link( contact );
        });
    }


 <script type="text/javascript" src="a.js"></script>

<form>
    <div id="contacts">Loading ...</div>
    <button class="add">New</button>
    <button class="save"> Save</button>
</form>
<script id="contactTmpl" type="text/x-jquery-tmpl">

    {{each contacts}}
        <div class="contact" data-index="${$index}">
            <label>First name</label> <input class="tomap" name="firstName" value="${firstName}">
            <label>Last name</label> <input class="tomap" name="lastName" value="${lastName}">
            <label>Number</label> <input class="tomap" name="phone" value="${phone}">
            <div class="tools">
                <button class="delete"</button>
            </div>
        </div>
    {{/each}}
</script>

this is the html and javascript code

I going to assume you are using jQuery templates, since that is what it looks like. If the template fails to render then it returns null which I believe is why you are getting the object has no method error. I trimmed your code down to just the template and the call to render the template and fixed the {{each}} and the ${$index} . I also assume the variable contacts is an array of objects.

A working fiddle is here: http://jsfiddle.net/brettwp/yfcuL/

Also the code:

<div id="contacts">EMPTY</div>
<script id="contactTmpl" type="text/x-jquery-tmpl">
    {{each(index,contact) contacts}}       
        <div class="contact" data-index="${index}">
            <label>First name</label> <input class="tomap" name="firstName" value="${contact.firstName}">
            <label>Last name</label> <input class="tomap" name="lastName" value="${contact.lastName}">
            <label>Number</label> <input class="tomap" name="phone" value="${contact.phone}">
            <div class="tools">
                <button class="delete"></button>
            </div>
        </div>
    {{/each}}
</script>

$(function(){
    $( "#contactTmpl" ).tmpl( {contacts: contacts} ).appendTo( "#contacts" );
});

You need to create the node first. Try this:

$('<div id="contactTmpl"/>').tmpl( {contacts:contacts} ).appendTo( "#contacts" );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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