How can i optimize this jquery code
Is there a shorter more optimized way to write the following code.
$("button.idiv").click(function(){
var elm = $('<div id=divid' + divId + ' class=aaa></div>');
elm.resizable().draggable({ containment: "p", stack:"div" }).appendTo('p');
divId++;
});
$("button.ispan").click(function(){
var elm = $('<img id=spanid' + spanId + ' class=aaas src="Dollar.png"/>');
elm.resizable().parent().draggable({ containment: "p", stack:"div" }).appendTo('p');
spanId++;
});
$("button.itext").click(function(){
var el开发者_运维问答m = $('<div id=textid' + textId + ' class=aaat>some text</div>');
elm.resizable().draggable({ containment: "p", stack:"div" }).appendTo('p');
textId++;
});
Since all three sets of code do almost the same thing except for some individual values, this is the perfect opportunity to consolidate the differences with some sort of configuration object:
var types = {
div: {
id: 1,
element: "<div>",
className: "aaa"
},
span: {
id: 1,
element: "<img src='Dollar.png'>",
className: "aaas",
parentDraggable: true
},
text: {
id: 1,
element: "<div>",
className: "aaat"
}
};
Then the code simply becomes:
$("button").click(function(){
var $this = $(this), t;
// See if the button has any class matching one of the defined "types"
for (var i in types) {
if (types.hasOwnProperty(i) && $this.hasClass("i" + i)) {
t = i;
break;
}
}
if (!t) return;
// Your condensed code
var elem = $(types[t].element)
.attr("id", t + "id").addClass(types[t].className)
.resizable();
if (types[t].parentDraggable) elem = elem.parent();
elem.draggable({ containment: "p", stack:"div" }).appendTo('p');
// Increment ID on the type itself
types[t].id++;
});
Are you looking to do something like this? The code might look like more, but I've tried to remove as much of the repeating as possible and also added lots of newlines and tabs to make it easier to read. Any difference in performance should be neglible.
$("button.idiv, button.itext, button.ispan").click(function(){
var $this = $(this),
draggableOptions = {
containment: "p",
stack:"div"
};
if ($this.is(".idiv, .itext")) {
var elm = $("<div>"),
cls = "aaa";
if ($this.is(".idiv")) {
id = "divid"+divId;
divId++;
} else {
id = "textid"+textId;
cls += "t";
textId++;
}
elm
.addClass(cls)
.attr("id", id)
.resizable();
} else {
var elm = $("<img>")
.attr("id", "spanid"+spanId)
.attr("src", "Dollar.png")
.addClass(cls+"s")
.resizable();
elm = elm.parent();
spanId++;
}
elm.draggable(draggableOptions)
.appendTo("p");
});
精彩评论