可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
The example I see posted all of the time seems like it\'s suboptimal, because it involves concatenating strings, which seems so not jQuery. It usually looks like this:
$.getJSON(\"/Admin/GetFolderList/\", function(result) {
for (var i = 0; i < result.length; i++) {
options += \'<option value=\"\' + result[i].ImageFolderID + \'\">\' + result[i].Name + \'</option>\';
}
});
Is there a better way?
回答1:
Andreas Grech was pretty close... it\'s actually this
(note the reference to this
instead of the item in the loop):
var $dropdown = $(\"#dropdown\");
$.each(result, function() {
$dropdown.append($(\"<option />\").val(this.ImageFolderID).text(this.Name));
});
回答2:
$.getJSON(\"/Admin/GetFolderList/\", function(result) {
var options = $(\"#options\");
//don\'t forget error handling!
$.each(result, function(item) {
options.append($(\"<option />\").val(item.ImageFolderID).text(item.Name));
});
});
What I\'m doing above is creating a new <option>
element and adding it to the options
list (assuming options
is the ID of a drop down element.
PS My javascript is a bit rusty so the syntax may not be perfect
回答3:
Sure - make options
an array of strings and use .join(\'\')
rather than +=
every time through the loop. Slight performance bump when dealing with large numbers of options...
var options = [];
$.getJSON(\"/Admin/GetFolderList/\", function(result) {
for (var i = 0; i < result.length; i++) {
options.push(\'<option value=\"\',
result[i].ImageFolderID, \'\">\',
result[i].Name, \'</option>\');
}
$(\"#theSelect\").html(options.join(\'\'));
});
Yes. I\'m still working with strings the whole time. Believe it or not, that\'s the fastest way to build a DOM fragment... Now, if you have only a few options, it won\'t really matter - use the technique Dreas demonstrates if you like the style. But bear in mind, you\'re invoking the browser\'s internal HTML parser i*2
times, rather than just once, and modifying the DOM each time through the loop... with a sufficient number of options. you\'ll end up paying for it, especially on older browsers.
Note: As Justice points out, this will fall apart if ImageFolderID
and Name
are not encoded properly...
回答4:
Or maybe:
var options = $(\"#options\");
$.each(data, function() {
options.append(new Option(this.text, this.value));
});
回答5:
The fastest way is this:
$.getJSON(\"/Admin/GetFolderList/\", function(result) {
var optionsValues = \'<select>\';
$.each(result, function(item) {
optionsValues += \'<option value=\"\' + item.ImageFolderID + \'\">\' + item.Name + \'</option>\';
});
optionsValues += \'</select>\';
var options = $(\'#options\');
options.replaceWith(optionsValues);
});
According to this link is the fastest way because you wrap everything in a single element when doing any kind of DOM insertion.
回答6:
I found this to be working from jquery site
$.getJSON( \"/Admin/GetFolderList/\", function( data ) {
var options = $(\"#dropdownID\");
$.each( data, function(key, val) {
options.append(new Option(key, val));
});
});
回答7:
Other approach with ES6
fetch(\'https://restcountries.eu/rest/v1/all\')
.then((response) => {
return response.json()
})
.then((countries) => {
var options = document.getElementById(\'someSelect\');
countries.forEach((country) => {
options.appendChild(new Option(country.name, country.name));
});
})
回答8:
I use the selectboxes jquery plugin. It turns your example into:
$(\'#idofselect\').ajaxAddOption(\'/Admin/GetFolderList/\', {}, false);
回答9:
$.get(str, function(data){
var sary=data.split(\'|\');
document.getElementById(\"select1\").options.length = 0;
document.getElementById(\"select1\").options[0] = new Option(\'Select a State\');
for(i=0;i<sary.length-1;i++){
document.getElementById(\"select1\").options[i+1] = new Option(sary[i]);
document.getElementById(\"select1\").options[i+1].value = sary[i];
}
});
回答10:
I\'ve read that using document fragments is performant because it avoids page reflow upon each insertion of DOM element, it\'s also well supported by all browsers (even IE 6).
var fragment = document.createDocumentFragment();
$.each(result, function() {
fragment.appendChild($(\"<option />\").val(this.ImageFolderID).text(this.Name)[0]);
});
$(\"#options\").append(fragment);
I first read about this in CodeSchool\'s JavaScript Best Practices course.
Here\'s a comparison of different approaches, thanks go to the author.
回答11:
function generateYears() {
$.ajax({
type: \"GET\",
url: \"getYears.do\",
data: \"\",
dataType: \"json\",
contentType: \"application/json\",
success: function(msg) {
populateYearsToSelectBox(msg);
}
});
}
function populateYearsToSelectBox(msg) {
var options = $(\"#selectYear\");
$.each(msg.dataCollecton, function(val, text) {
options.append(
$(\'<option></option>\').val(text).html(text)
);
});
}
回答12:
I hope it helps.
I usually use functions instead write all code everytime.
$(\"#action_selector\").change(function () {
ajaxObj = $.ajax({
url: \'YourURL\',
type: \'POST\', // You can use GET
data: \'parameter1=value1\',
dataType: \"json\",
context: this,
success: function (data) {
json: data
},
error: function (request) {
$(\".return-json\").html(\"Some error!\");
}
});
json_obj = $.parseJSON(ajaxObj.responseText);
var options = $(\"#selector\");
options.empty();
options.append(new Option(\"-- Select --\", 0));
$.each(ajx_obj, function () {
options.append(new Option(this.text, this.value));
});
});
});
回答13:
I have been using jQuery and calling a function to populate drop downs.
function loadDropDowns(name,value)
{
var ddl = \"#Categories\";
$(ddl).append(\'<option value=\"\' + value + \'\">\' + name + \"</option>\'\");
}
回答14:
function LoadCategories() {
var data = [];
var url = \'@Url.Action(\"GetCategories\", \"InternalTables\")\';
$.getJSON(url, null, function (data) {
data = $.map(data, function (item, a) {
return \"<option value=\" + item.Value + \">\" + item.Description + \"</option>\";
});
$(\"#ddlCategory\").html(\'<option value=\"0\">Select</option>\');
$(\"#ddlCategory\").append(data.join(\"\"));
});
}
回答15:
here is an example i did on change i get children of the first select in second select
jQuery(document).ready(function($) {
$(\'.your_select\').change(function() {
$.ajaxSetup({
headers:{\'X-CSRF-TOKEN\': $(\"meta[name=\'csrf-token\']\").attr(\'content\')}
});
$.ajax({
type:\'POST\',
url: \'Link\',
data:{
\'id\': $(this).val()
},
success:function(r){
$.each(r, function(res) {
console.log(r[res].Nom);
$(\'.select_to_populate\').append($(\"<option />\").val(r[res].id).text(r[res].Nom));
});
},error:function(r) {
alert(\'Error\');
}
});
});
});enter code here