【问题标题】:jQuery - using user input values in text template - best practice?jQuery - 在文本模板中使用用户输入值 - 最佳实践?
【发布时间】:2018-06-30 15:10:20
【问题描述】:

我有一个表单,用户可以在其中输入几十个值来生成报告。所需的文本输出具有特定格式,因此为了生成它,我一直在这样做:

var textoutput = "The house on " + $("#usercontent1").val() + " has " 
+ $("#usercontent2").val() + " bathrooms and ";
+ $("#usercontent3").val() + "bedrooms.";

等等。有没有更有效的方法来做到这一点,使其更具可读性? 目前,考虑到输入字段的数量,这个文本块有几百行长,而且有点笨拙。

【问题讨论】:

    标签: jquery text input


    【解决方案1】:

    for 循环怎么样...

    $(document).ready(function() {
    
    console.log('1. Document is ready.');
    
    // Run the App.
    runApplication();
    
    });
    
    // We create a variable called runApplication and assign it a function runApplication()
    var runApplication = function runApplication() {
    
    console.log('1.1 runApplication() function called.');
    
    // We make a reference to all element inputs of type text inside form1..
    var elements = document.querySelectorAll('#form1 input[type=text]');
    
    // then we create a Global string variable to append stuff to...
    var final_string = '';
    
    // then for each and every punt of type text found inside form1...
    for (var i = 0; i < elements.length; i++) {
        // if it's really somthing other than nothing....
        if(elements[i] = true) {
            // append current input text value in the lopp to variable final_string
            final_string = final_string + elements[i].value + ' ';
            console.log(elements[i].value);
        }
    }
    
    // output final_string with all input text values...
    // ..joined together by the for loop.
    console.log(final_string);
    
    };
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <form id="form1">
    <input type="text" value="1">
    <input type="text" value="2">
    <input type="text" value="3">
    <input type="text" value="4">
    <input type="text" value="5">
    </form>

    【讨论】:

    • 您好,限制之一是每个字段在用户输入之前或之后可能有不同的文本,以适应句子结构。
    猜你喜欢
    • 2010-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-10
    • 1970-01-01
    相关资源
    最近更新 更多