简体   繁体   中英

Why am I getting [object Object] instead of my expected HTML when refactoring jQuery code?

I'm trying to clean up my code, and I find in my script many snippets that are similar to the following:

$msg.html('<a href="#" data-userName=' + msg.user +
      ' class="userName" onClick="showCurrUsersMsgs(this);">@' + msg.user + '</a>' + '<span class="timestamp"> <b>&middot;</b> ' + 
      jQuery.timeago(msg.created_at) +'</span></br>' + 
      msg.message);

I tried doing something like

var $userProfile = $('<a href="#" data-userName=' + msg.user +
      ' class="userName" onClick="showCurrUsersMsgs(this);">@' + msg.user + '</a>');
var $timeStamp = $('<span class="timestamp"> <b>&middot;</b> ' + 
      jQuery.timeago(msg.created_at) +'</span>'); 
$msg.html($userProfile + $timeStamp + '</br>' + msg.message);

to make it more readable, but then the page doesn't build correctly. Instead, it shows something like [Object][Object] .

Why is this happening, and how do I fix this error?

This is a clear (long, though) way of refactoring your html-generating jQuery code:

var $a = $('<a>', {
  'href': '#',
  'data-userName': msg.user,
  'class': 'userName',
  'html': '@' + msg.user
}).on('click', function() { showCurrUsersMsgs(this);});

var $span = $('<span>', {
  'class': 'timestamp',
  'html': '<b>&middot;</b>' + msg.created_at
});

var $p = $('<p>', {html: msg.message});

var $html = $a.add($span).add($('<br>')).add($p);

You can't "add" two jQuery objects together. You should just be building up the HTML fragments as strings, and then concatenating the strings together:

var userProfile = '<a href="#" data-userName=' + msg.user +
      ' class="userName" onClick="showCurrUsersMsgs(this);">@' + msg.user + '</a>';
var timeStamp = '<span class="timestamp"> <b>&middot;</b> ' + 
      jQuery.timeago(msg.created_at) +'</span>'; 
$msg.html(userProfile + timeStamp + '</br>' + msg.message);

That said, if you're actually interested in cleaning this up, you should stop building up your HTML using simple string concatenation. Choose a real templating library like Handlebars, HTMLBars, Jade, etc etc.

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