【问题标题】:Jquery - How to read a txt file and append into a formJquery - 如何读取 txt 文件并附加到表单中
【发布时间】:2013-04-19 20:57:33
【问题描述】:

我有几个类似内容的文本文件:

<select name='CitySearch' id='CitySearch'>
   <option value=''>- Select a City -</option>
   <option value=''>-----------</option>
   <option value='Bejuco'>Bejuco</option>
   <option value='Esterillos'>Esterillos</option>
</select>

当然每一个都是不同的内容。无论文件名如何,我们都可以使用example.txt

我有一张地图,如果您单击任何区域,脚本必须将 txt 附加到表单中。这是点击时的功能:

// Assigning an action to the click event
$(this).click(function(e) {
    var country_id = $(this).attr('id').replace('area_', '');

    if($("div[id^='area_']").length = 1){
        $("div[id^='area_']").remove(); //remove the last inserted select option
        }
var append_data = '<div id="area_'+country_id+'">**INSERT HTML FROM FILE HERE**</div>';
$("#text_boxes").append(append_data); //append new select options in main div
    });

我知道这是基本的东西,但我对 jquery 没有太多经验。

【问题讨论】:

    标签: jquery file append


    【解决方案1】:

    您可以使用.load() 获取文件的内容并将其插入到匹配的元素中。

    var append_data = '<div id="area_'+country_id+'"></div>';
    $("#text_boxes").append(append_data); //append new select options in main div
    
    $("#area_"+country_id).load("path/to/file.html"); // load html file
    

    【讨论】:

      【解决方案2】:

      对文件 url 执行 ajax 调用并将响应附加到字符串。

          $(this).click(function(e) {
              var country_id = $(this).attr('id').replace('area_', '');
      
              if($("div[id^='area_']").length = 1){
                  $("div[id^='area_']").remove(); //remove the last inserted select option
                  }
                appendNewResult(country_id);
              });
      function appendNewResult(country_id){
              $.get(filepath,function(response){
                            var append_data = '<div id="area_'+country_id+'">' + response +'</div>';
          $("#text_boxes").append(append_data); //append new select options in main div
      
              });
      }
      

      【讨论】:

      • 这使用$.get() 与我的.load() 答案完全相同,但多了几行代码。可能值得注意的是,此方法允许您在完整的处理程序中执行更多操作。两者都适用于您的要求。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-26
      • 1970-01-01
      • 2021-08-11
      • 2015-03-01
      • 1970-01-01
      相关资源
      最近更新 更多