无法将html插入jQuery对象

时间:2014-03-05 03:29:22

标签: javascript jquery html css backbone.js

我想在我的页面上将一些html插入div中,但它无法正常工作。我试图插入模板化的html $('#users-found')。html(tpl)但它不起作用。当我使用它时,它可以工作。$ el.append,但我希望每次搜索用户时都要更改它。有什么想法吗?

define([
  'jquery',     
  'underscore', 
  'backbone',
  'parse',
  'text!templates/searchUsers_tpl.html',
  'text!templates/userList_tpl.html'    
], function($, _, Backbone, Parse, SearchUsersTpl, UserListTpl){
var SearchUsersView = Backbone.View.extend({

    el: '#content',

    initialize: function(){
        console.log('search users');
        this.render();
    },

    render: function(){
        this.$el.html(SearchUsersTpl);
    },

    events: {
        'click #submit-search': 'search'
    },

    search: function(){
        var self = this;
        var input = $('#search-users-input').val();
        console.log('search input: ' + input);
        var query = new Parse.Query(Parse.User);
        query.equalTo('username', input);
        query.find({
            success: function(results){
                console.log("Successfully retrieved " + results.length + " users.");

                for (var i = 0; i < results.length; i++) {
                    var object = results[i];
                    console.log(object.id + ' - ' + object.get('username'));
                }

                var tpl = _.template(UserListTpl, {users: results});
                $('#users-found').html(tpl);
            },
            error: function(){
                console.log('search for user failed');
            }
        });
    }

}); 
  return SearchUsersView;      
});

在制作视图时加载的html,SearchUsersTpl

<h1>Find Friends</h1>
<br>
<br>
<input id='search-users-input' type="search" value="" placeholder="search username" class="topcoat-search-input">
<button type='search' id='submit-search' class='topcoat-button'>Search</button>
<br>
<br>
<div id='#users-found'></div>

模板

<div>
 <% _.each(users, function(user) { %> 
    <li><%= user.get('username') %></li> 
 <% }); %>
</div>

2 个答案:

答案 0 :(得分:2)

您的DIV ID错误。它应该是&lt; div id ='users-found'&gt;&lt; / div&gt;不是&lt; div id ='#users-found'&gt;&lt; / div&gt;

has h仅用作选择器,但在将其指定为ID时不需要。

答案 1 :(得分:1)

确保将用户模板转换为jQuery对象。尝试更换:

$('#users-found').html(tpl);

$(tpl).appendTo($('#users-found').empty());