我如何优化此jQuery代码 [英] How can i optimize this jquery code

查看:83
本文介绍了我如何优化此jQuery代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否存在一种更短,更优化的方式来编写以下代码.

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

推荐答案

您是否正在做这样的事情?该代码可能看起来更多,但是我尝试删除尽可能多的重复代码,并且还添加了许多换行符和选项卡,以使其更易于阅读.性能上的任何差异都应该忽略不计.

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

这篇关于我如何优化此jQuery代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆