2013-04-25 43 views
0

我有几个文本文件,这样的内容是这样的:jQuery的 - 如何阅读txt文件,并追加到形式

<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 
    }); 

我知道这是basicall的东西,但我没有太多的经验与jQuery。

回答

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

哇,真的有效!谢谢 – user2321336 2013-04-25 20:12:44

0

对文件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 

     }); 
} 
+0

这使用'。.get()'与我的'.load()'答案完全相同,但是有几行代码。值得注意的是,这种方法可以让你在完整的处理程序中做更多的事情。两者都适用于您的要求。 – jrummell 2013-04-25 20:19:04

+0

@jrummell,op是添加额外的html代码,为什么我使用得到。 – Anoop 2013-04-25 21:13:12