我该如何优化这个jquery代码

时间:2011-01-08 21:27:56

标签: jquery optimization

是否有更短的更优化的方式来编写以下代码。

$("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 elm = $('<div id=textid' + textId + ' class=aaat>some text</div>');
        elm.resizable().draggable({ containment: "p", stack:"div" }).appendTo('p');
        textId++;
});

2 个答案:

答案 0 :(得分:1)

由于对于某些单独的值,所有三组代码几乎 ,这是与某种配置对象合并差异的绝佳机会:

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"
    }
};

然后代码变成:

$("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++;
});

答案 1 :(得分:0)

你想做这样的事吗?代码可能看起来更多,但我试图尽可能多地删除重复,并添加了许多换行符和标签,以便于阅读。任何性能差异都应该可以忽略不计。

$("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");
});