开发者

cant pass text string into jquery function?

What's wrong with my jquery script?

Here's the script

function debug(message){
  $("body").append("<div id=\"debug\">"+ $(message) +"</div>"):
}
debug("show this debug message in the div");

Here's the resulting html I get

<div id="debug">[object Object]</div>

The html that I expect is this

<div id="debug">sh开发者_运维知识库ow this debug message in the div</div>


You're converting a string to a jquery object using $(message). basically, you're making message no longer a string but a selector to jquery. Try the following:

function debug(message){
  $('body').append($('<div>').attr('id','debug').text(message));
}

note I use .attr and .text as this is a tad bid safer when appending information.

EDIT Also, another thing to note: ID is a unique identifier in HTML. for this reason, if you're calling this function multiple times, you may want to either assign a perm. "div" to alter the .text() value of, or consider using a debug [CSS] class for the div.


You are pasting an object in, $(message), instead of the variable message. Try this:

    function debug(message){
      $("body").append("<div id=\"debug\">"+ message +"</div>"):
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜