jquery DOM 操作 - 更有效的方法

发布于 2024-11-29 12:36:12 字数 4371 浏览 1 评论 0原文

我正在为移动 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>

I am doing a a lot of repeating segments of code for a mobile html app. To asve download time, I have been trying to reduce html code and automate with jQuery, but jquery is getting quite verbose. Here is example. Can this type of thing be made less verbose and more efficient?

<!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>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

甜中书 2024-12-06 12:36:12

逻辑看起来不错,但您可以通过缓存局部变量而不是多次查找它们来临时提高代码的性能。看看这个

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

The logic looks good but you can improvise on the performance of the code by caching the local variables instead of finding them multiple times. Take a look at this

$(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');                                    
        }
});
椵侞 2024-12-06 12:36:12

考虑使用 jQuery 模板

创建一个输入元素模板,如下所示:

<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 代码将变得更易于管理!

为输入定义数据集:

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 结果数据。

Consider using jQuery Templates

Create a single input element template like this:

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

Then you can create a template for group of inputs like this:

<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>

Now, using both of these, the actual jQuery code will become a lot more manageable!!

Define your DataSet for inputs:

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

Finally one single line to cast and append:

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

I know the actual values and logic you have is not matched perfectly but essentially this is how you should do this kind of thing. jQuery Templates allow you much better code manageability and cleaner DOM manipulation for situations like this when you want to insert variable data based HTML elements to the page.

Also, these are used extensively with AJAX calls, because you can display POST result data effortlessly.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文