【问题标题】:Loading template with variables from form fields using jQuery & php使用 jQuery 和 php 从表单字段中加载带有变量的模板
【发布时间】:2010-05-14 18:08:58
【问题描述】:

我正在尝试创建一个生成 html 模板的表单。我在页面上的隐藏 div 中有模板,并且正在使用 jQuery 使用模板 html 创建一个新窗口,但我不知道如何将表单字段的内容加载到模板中。我知道我可能应该使用 AJAX,但我不知道从哪里开始。

【问题讨论】:

    标签: php jquery forms


    【解决方案1】:

    假设你有这个模板:

    <div class="template">
        <p class="blah"></p>
        <p class="foo"></p>
    </div>
    

    还有这个表格:

    <form>
        <input name="blah" class="blah"/>
        <input name="foo" class="foo"/>
    </form>
    

    因此,对于本示例,我们将假设表单元素通过每个对应元素的公共类映射到模板元素:

    $("form input").each(function() {
        $(".template").find("." + $(this).attr("class")).html(this.value);
    });
    

    在这里试试:http://jsfiddle.net/dx2E6/

    【讨论】:

      【解决方案2】:

      我一直在使用的一个技巧是使用&lt;script type="text/html"&gt; 标签。浏览器不渲染代码,所以我做的是这样的:

      <script type="text/html" id="template">
      <div>
        <div class="some_field">{name}</div>
        <h4>{heading}</h4>
        <p>{text}</p>
      </div>
      </script>
      

      你的表单是这样的:

      <form>
        <input type="text" name="name" />
        <input type="text" name="heading" />
        <input type="text" name="text" />
      </form>
      

      那么您的 javascript 代码将类似于:

      $(document).ready(function(){
      
        var tpl = $('#template').html();
      
        $('form input').each(function(){
          tpl.replace('{'+$(this).attr('name')+'}',$(this).val());
        });
      
        $('div.some_destination').html(tpl);
      
      });
      

      希望对您有所帮助。如果您对此方法有更多疑问,请告诉我。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-05-04
        • 2022-01-05
        • 2015-05-25
        • 1970-01-01
        • 1970-01-01
        • 2011-02-03
        • 2018-06-05
        • 2018-01-28
        相关资源
        最近更新 更多