var str = prompt("What is your name?");
var str1=$(str).html('<b>'+str+'</b>');
alert(s开发者_JS百科tr1);
By above code I'm getting [object object]
as output ,. please help
alert(str1.html());
is what you are after.
each function in jquery returns a jquery object so
.html('<b>'+str+'</b>')
returns an object, not the text inside the element.
First of all, let's look up html()
in the jQuery API:
- http://api.jquery.com/html/
It has two variations. If you pass an argument, the method signature is this:
.html( htmlString ) Returns: jQuery
So it returns a jQuery
object. And objects don't have any interesting to show inside an alert. Now, what can you do with jQuery objects that represent a DOM node? Well, you can read back their HTML code:
alert(myNode.html());
... or you can read their plain text value:
alert(myNode.text());
Now, let's look at your code:
var str = prompt("What is your name?");
Since prompt() returns either a string (if the user typed something and hit OK) or null
(if the user hit Cancel), str
will either be an arbitrary string or null
.
var str1=$(str)
You are calling jQuery with an arbitrary string so you'll get an arbitrary jQuery object. If the user types john
you'll run $("john")
. That means: match any element that contains a <john></john>
tag. If the user types <h1>Hi</h1>
you'll create a first level title. And so on...
.html('<b>'+str+'</b>');
Now you pick whatever you got in the first step and tell jQuery to change its HTML to some arbitrary content: .html("<b>john</b>")
or .html("<b><h1>Hi</h1></b>")
...
alert(str1);
... and we get nothing interesting so far ;-)
This is correct because your are setting the HTML and then the function returns the jQuery object
var str1=$(str).html('<b>'+str+'</b>').html();
now str1 will have the HTML string.
Edit:
But as DarthJDG pointed out correctly wrapping a string (the return value of prompt()
) into a jQuery object and the stetting some HTML to it makes no real scense.
The statment $(str).html('<b>'+str+'</b>');
is setting the html
of $(str)
, and then returning $(str)
back from the call (for chaning purposes).
I've held back on suggesting a soluton because I'm not entirely sure what you are trying to achieve. Can you be alittle more explicit in your question?
Yes, and that is exactly what you should expect. By passing an argument to .html()
, you're invoking the method that returns a jQuery
(i.e., an object).
If, instead, you want to return the (HTML) value of the element, you should alert(str1.html())
, thus invoking the method which returns a string.
You should do:
alert($(str).html());
YOur code wasn't working because $(str).html('<b>'+str+'</b>');
return a jquery object, not an string.
Cheers
精彩评论