I am using JQuery and Jquery UI to create a dialog box which contains a custom form. I have a basic dialog frame, which has a tool appended to its body. So the basic structure of my dialog is Jquery UI Frame > Dialog Frame > ToolBody > Tool开发者_JAVA百科 Content.
Code:
ToolManager.prototype.showTool = function(tool){
var $container = $("#" + this.id);
var $tool = $("#" + tool.id);
var $toolBody = $("#" + this.toolBodyId);
$container.dialog({
resizable: false,
modal: true,
width: tool.width,
stack: true,
height: 'auto',
draggable: true,
close: this.tearDown,
open: this.setup
});
$tool.removeClass("hidden");
$toolBody.append($tool.html());
//$toolBody.append($tool);
$container.show();
};
This works despite its need for refactoring, however before using this method I was attempting to use the commented out line:
$toolBody.append($tool);
This method wreaked havoc on my layout and caused the appended content to be blocked from receiving focus. Can anyone explain the difference between appending a Jquery Object and appending an html string? Or why it behaved this way?
This line of code:
$toolBody.append($tool);
Will take the nodes in $tool, and move them to the first (hopefully, the only) node of $toolBody.
This line of code:
$toolBody.append($tool.html());
Turns all of the HTML code inside of $tool and turns it into a string. The jQuery Append method has sugar around it and is smart enough to realize that when you're attempting to append()
a string, it should first turn that string into a set of nodes.
Effectively, you're moving the nodes in the former and case and doing a (poor) clone of the nodes inside of $tool in the latter case.
AFAIK, an object is a reference to a DOM element, and not a copy of that element.
So can you can use html() to show all it's html content, or text() to show all it's text content, with tags removed.
You might be better off using clone() which makes an exact copy, and can be used in conjunction with appendTo()
Something like: $(tool).clone().appendTo().toolBody
精彩评论