如何在JavaScript中加载外部文件?

约瑟夫

我正在编写一个脚本,您可以在其中添加和删除语言的下拉列表。我可以使用它,但是我的问题是是否有一种方法可以将代码的select标签部分外部化,因为我将有100多个选项,并在单击链接时将其加载到JavaScript中。我不想在脚本中包含100个选项标签。在PHP方面,我使用include语句加载我的选项列表。

这是我的问题所在。

$(function() {
    var scntDiv = $('#container');
    var i = $('#container p').size() + 1;

    $('#addScnt').live('click', function() {
        $('<p><select>I DONT WANT TO HAVE 100 OPTION TAGS HERE</select></p>').appendTo(scntDiv);
        i++;
        return false;
    });
});

这是我的代码,在脚本中带有一些选项标签。

完整代码

bhanu.cs

您可以将所有数据放入如下的Json文件中(例如):

{"student": [
  {
    "id": "1",
    "name": "Person1"
  },
  {
    "id": "2",
    "name": "Person2"
  },
  {
    "id": "3",
    "name": "Person3"
  }
]}

现在单击实现以下

     $('#addScnt').on('click', function() {
     //get a reference to the select element
$('<p><select id="test"></select></p>').appendTo(scntDiv);
        var $select = $('#test`enter code here`');</code>

        //request the JSON data and parse into the select element
        $.getJSON('student.JSON', function(data){

          //clear the current content of the select
          $select.html('');

          //iterate over the data and append a select option
          $.each(data.student, function(key, val){ 
            $select.append('<option id="' + val.id + '">' + val.name + '</option>');
          })
        });
        });

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章