jquery DOM操作 - 更有效的方法

时间:2011-08-14 16:37:17

标签: jquery dom jquery-mobile append

我正在为移动HTML应用程序做很多重复的代码段。为了下载时间,我一直在尝试减少HTML代码并使用jQuery自动化,但jquery变得非常冗长。这是一个例子。这种事情可以减少冗长和有效吗?

<!DOCTYPE html>
<html>
<head>

<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0b2/jquery.mobile-1.0b2.min.css" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.2.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/mobile/1.0b2/jquery.mobile-1.0b2.min.js"></script>   
<script type="text/javascript">

tplCnf = "\n\n\
        <center>\n\
        <div data-role='content' data-theme='b'>\n\
                <fieldset data-role='controlgroup' data-type='horizontal'>\n\
                    <input type='radio' name='FMT' id='' value='S' checked='checked' /><label   name='FMT' for=''>Serial</label>\n\
                    <input type='radio' name='FMT' id='' value='P' /><label                     name='FMT' for=''>Parallel</label>\n\
                    <input type='radio' name='FMT' id='' value='O' /><label                     name='FMT' for=''>Other</label>\n\
                </fieldset>\n\
        </div>\n\
        </center>";

$(document).ready(function()
{
    /* This is used to populate configuration types */          
    var groups = ['A','B','C','D','E','F'];

    /* add data config type types */
        for (var myLetters in groups){
            // clone fragment of html
            myTmpl = $(tplCnf); 

            // create a unique name for Configuratin radio boxes and corresponding labels
            myTmpl.find('input[name="FMT"]')                
                .attr("name", "FMT-"+groups[myLetters]);                
            myTmpl.find('label[name="FMT"]')                
                .attr("name", "FMT-"+groups[myLetters]);

            // apply id name to first configuration radio box 
            name1 = "preConfigRadio-" + groups[myLetters] + "1";            
            myTmpl.find('input[name="FMT-"+ groups[myLetters]]:eq(0)')
                .attr("id", name1)
            myTmpl.find('label[name="FMT-"+ groups[myLetters]]:eq(0)')
                .attr("for", name1);

            // apply id name to second configuration radio box 
            name2 = "preConfigRadio-" + groups[myLetters] + "2";            
            myTmpl.find('input[name="FMT-"+ groups[myLetters]]:eq(1)')
                .attr("id", name2);
            myTmpl.find('label[name="FMT-"+ groups[myLetters]]:eq(1)')
                .attr("for", name2);

            // apply id name to third configuration radio box 
            name3 = "preConfigRadio-" + groups[myLetters] + "3";
            myTmpl.find('input[name="FMT-"+ groups[myLetters]]:eq(2)')
                .attr("id", name3);
            myTmpl.find('label[name="FMT-"+ groups[myLetters]]:eq(2)')
                .attr("for", name3);

            // then append
            myTmpl.appendTo("#placeholder"+groups[myLetters]).trigger('create');                                    
        }
});

</script>   

</head> 
<body>  

<!-- ***   Navigation bar   *** -->
<div data-role="page"  id="preHelpTab">
<div data-role="header" data-position="inline">

<input type="hidden" id="preBeginRequestDtls" name="BeginRequestDtls" value=""  />

        <div id='groupA' class='preGroups'> 
        This is Group A
            <div id='placeholderA' ></div>  

        </div>

        <div id='groupB' class='preGroups'> 
        This is Group B
            <div id='placeholderB' ></div>  
        </div>

        <div id='groupC' class='preGroups'> 
        This is Group C
            <div id='placeholderC' ></div>  
        </div>

        <div id='groupD' class='preGroups'> 
        This is Group D
            <div id='placeholderD' ></div>  
        </div>

        <div id='groupE' class='preGroups'> 
        This is Group E
            <div id='placeholderE' ></div>  
        </div>

        <div id='groupF' class='preGroups'> 
        This is Group F
            <div id='placeholderF' ></div>  
        </div>
</div>
</div>

2 个答案:

答案 0 :(得分:0)

逻辑看起来不错,但您可以通过缓存局部变量而不是多次查找它来即兴表达代码的性能。看看这个

$(document).ready(function()
{
    /* This is used to populate configuration types */          
    var groups = ['A','B','C','D','E','F'], inputs, label, name;

    /* add data config type types */
        for (var myLetters in groups){
            // clone fragment of html
            myTmpl = $(tplCnf); 

            // create a unique name for Configuratin radio boxes and corresponding labels
            inputs = myTmpl.find('input[name="FMT"]')                
                .attr("name", "FMT-"+groups[myLetters]);                
            lables = myTmpl.find('label[name="FMT"]')                
                .attr("name", "FMT-"+groups[myLetters]);

            for(var i =0;i<3;i++){
               name = "preConfigRadio-" + groups[myLetters] + (i+1);            
               inputs.eq(i).attr("id", name)
               labels.eq(i).attr("for", name);
            }

            // then append
            myTmpl.appendTo("#placeholder"+groups[myLetters]).trigger('create');                                    
        }
});

答案 1 :(得分:0)

考虑使用jQuery Templates

创建一个像这样的单个输入元素模板:

<script id="inputTemplate" type="text/html">
    <input type='radio' name="${groupName}" id="${id}" value="${value}" />
    <label name="${labelName}" for="${for}">${labelValue}</label>
</script>

然后你可以为这组输入创建一个模板:

<script id="groupTemplate" type="text/html">
    <center>
        <div data-role='content' data-theme='b'>
            <fieldset data-role='controlgroup' data-type='horizontal'>
                ${inputItem}
            </fieldset>
        </div>
    </center>
</script>

现在,使用这两者,实际的jQuery代码将变得更易于管理!!

为输入定义DataSet:

var inputDataSet = [
    { groupName: "FMT-A", id: 1, value: "", labelName: "1A", for: "", labelValue: "123" },
    { groupName: "FMT-A", id: 2, value: "", labelName: "2A", for: "", labelValue: "123123" },
    { groupName: "FMT-A", id: 3, value: "", labelName: "3A", for: "", labelValue: "1231231" }
]

最后一行投射和追加:

$("#groupTemplate").tmpl($("#inputTemplate").tmpl(inputDataSet)).appendTo("#placeholder");

我知道你所拥有的实际价值和逻辑并不完美匹配,但实质上这就是你应该如何做这件事。当您想要将基于可变数据的HTML元素插入页面时,jQuery模板可以为这种情况提供更好的代码可管理性和更清晰的DOM操作。

此外,这些广泛用于AJAX调用,因为您可以毫不费力地显示POST结果数据。