在jquery String中插入一个数组

时间:2018-04-03 15:58:15

标签: jquery arrays

您好我对jquery中的数组和字符串有疑问

var fonts = ["<option>Arial</option>","<option>Arial Black</option>","<option>Calibri</option>","<option>Courier New</option>","<option>Comic Sans MS</option>","<option>Garamond</option>","<option>Georgia</option>","<option>Impact</option>","<option>Tahoma</option>","<option>Palatino</option>","<option>Times New Roman</option>","<option>Tahoma</option>","<option>Verdana</option>"];

function addselection(){ var string = "<select>fonts</select>";
 $('#id').append(string);}

我不知道它是如何工作的......我只是需要建议或回答谢谢

2 个答案:

答案 0 :(得分:1)

你有一个数组,所以你需要迭代这个数组的所有位置并附加每个数组。最简单的方法是使用for循环,然后在每次迭代中附加选项,如下所示。

还有另外一种方法可以做到这一点,就像你会看到别人的答案一样,但我认为(我的意见),对于begginers(如果你的话),这是最好的选择)

var fonts = ["<option>Arial</option>","<option>Arial Black</option>","<option>Calibri</option>","<option>Courier New</option>","<option>Comic Sans MS</option>","<option>Garamond</option>","<option>Georgia</option>","<option>Impact</option>","<option>Tahoma</option>","<option>Palatino</option>","<option>Times New Roman</option>","<option>Tahoma</option>","<option>Verdana</option>"];

function addselection(){
  for (var i =0; i < fonts.length; i++){
    var myOption = fonts[i];
    $('#id').append(myOption);
  }
}
 
 addselection();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='id'></select>

答案 1 :(得分:0)

要达到预期效果,请使用以下选项

循环字体数组并附加到选择

&#13;
&#13;
var fonts = ["<option>Arial</option>","<option>Arial Black</option>","<option>Calibri</option>","<option>Courier New</option>","<option>Comic Sans MS</option>","<option>Garamond</option>","<option>Georgia</option>","<option>Impact</option>","<option>Tahoma</option>","<option>Palatino</option>","<option>Times New Roman</option>","<option>Tahoma</option>","<option>Verdana</option>"];

function addselection(){ 
  var string = "<select>fonts</select>";
 $('#id').append(string);
  $.each(fonts, function(key, value) {   
     $('select')
         .append($(value)); 
});
}

addselection();
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id ="id"></div>
&#13;
&#13;
&#13;

代码示例 - and can lead to bugs when not used correctly