Jquery - 如何读取文本文件并附加到表单中

时间:2013-04-25 19:57:46

标签: jquery file append

我有几个像这样的内容的文本文件:

<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没有太多经验。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

        });
}
相关问题