cant pass text string into jquery function?

六月ゝ 毕业季﹏ 提交于 2020-01-03 17:21:30

问题


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">show this debug message in the div</div>

回答1:


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

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



回答2:


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.



来源:https://stackoverflow.com/questions/4643853/cant-pass-text-string-into-jquery-function

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