If I look at the JQuery doc @ http://api.jquery.com/jQuery/#jQuery2, it says
...If a string is passed as the parameter to $(), jQuery examines the string to see if it looks like HTML ...
However, what if I wa开发者_如何学Gont this behavior to occur all the time? I'm passing in a variable to $()
, and I always want the variable to be interpreted as a HTML, not selector.
One way to do it is wrap the variable with a <span>
tag, I don't want to add unnecessary DOM to the tree.
The variable will be interpreted as the value it references. So if your variable contains "<span>"
, you'll get a span
element back.
var tag = "<span>";
var $span = $( tag ); // returns a new span DOM element wrapped in a jQuery object
or if you meant that the variable will only contain the tag name "span"
, then concatenate the brackets.
var tag = "span";
var $span = $( "<" + tag + ">" );
EDIT: jQuery lets you create DOM elements this way. If you wanted to create something else like a text node, you can use a container as you suggested, but you don't need to add it to the DOM.
var txt = "this will be a text node";
var textNode = $( "<span>", {text: txt} ).contents();
If you append textNode
to the DOM, you will only be getting the content of the span.
I believe if you want to be absolutely certain, without having control of the variable's contents, you'll have to do the wrapper thing or use replaceWith
or append
instead, since those APIs aren't ambiguous. If you can, do the latter, because the wrapper thing can bite you. (For instance, if the variable contains a table row that will ultimately be appended to a table, you can't use a span
or div
wrapper; but you can't use a table
wrapper for something that isn't a table row.)
For instance, instead of
$(varname).appendTo(dest);
you can do
dest.append(varname); // Or $(dest).append(varname) if `dest` isn't already a jQuery instance
...and instead of
$(varname).replaceAll(targets);
you'd do
targets.replaceWith(varname); // Or $(targest).replaceWith(varname)
In JQuery 1.8 (currently in beta), they're introducing $.parseHTML, which is suppose to perform this task.
http://blog.jquery.com/2012/06/22/jquery-1-8-beta-1-see-whats-coming-and-going/
What exactly do you mean with "HTML object" ?
If you mean a string without any HTML-Elements included, you can create a textNode of it and assign this to $() :
$(document.createTextNode(variable))
HTML passed to jQuery will get converted to DOM elements, but only valid HTML. If you pass a tag properly <tag>
or hierarchy thereof you'll get converted code. If you pass random text, unbalanced tags or something odd, you'll get a selector of some description.
精彩评论