So basicly I'm gathering data from a file, this data is as follows:
所以我基本上是从文件中收集数据,这个数据如下:
[{"course_id":"1","name":"test"},
{"course_id":"2","name":"test1"},
{"course_id":"3","name":"test2"}]
Javascript/jquery code is as follows:
Javascript / jquery代码如下:
function createSelect(data) {
for(i = 0; i < data.length; i++) {
console.log(data[i]['course_id'], data[i]['name']);
var select = $('<select></select');
$(this).parent().append(select);
}
}
$(document).ready(function () {
$('.note').click(function () {
switch($(this).attr('id')) {
case '1': id = 'getCourse'; break;
case '2': break;
case '3': break;
case '4': break;
case '5': break;
};
if(id != '') {
$.ajax({
url: './functions/' + id + '.php',
cache: false,
dataType: 'json',
success: function(data) {
createSelect(data);
},
error: function (request, status, error) {
console.log('error', error);
}
});
};
});
});
I'm working towards a function that places the data in options of the select dom object, I have the code for that already written. This is all about the select dom object not being made.
我正在努力将一个函数放在select dom对象的选项中,我已经编写了代码。这是关于未制作的选择dom对象的全部内容。
Unfortunatly, even while the data is succesfully writen in de console, the select object can not be made. Can someone please explain to me what I'm missing?
不幸的是,即使数据在de控制台中成功写入,也无法生成选择对象。有人可以向我解释我错过了什么吗?
2 个解决方案
#1
use
$('.note').parent().append(select);
instead of
$(this).parent().append(select);
cause $(this)
in your function not refer to anything
因为你的函数中的$(this)没有引用任何东西
#2
Your problem is $(this)
in createSelect
function, You need pass the element to createSelect
function.
你的问题是$(this)在createSelect函数中,你需要将元素传递给createSelect函数。
function createSelect(element, data) {
for(i = 0; i < data.length; i++) {
var select = $('<select></select');
//Use element
element.parent().append(select);
}
}
$(document).ready(function () {
$('.note').click(function () {
var element = $(this); //Store this reference
$.ajax({
success: function(data) {
createSelect(element, data); //pass the element
}
});
};
});
});
#1
use
$('.note').parent().append(select);
instead of
$(this).parent().append(select);
cause $(this)
in your function not refer to anything
因为你的函数中的$(this)没有引用任何东西
#2
Your problem is $(this)
in createSelect
function, You need pass the element to createSelect
function.
你的问题是$(this)在createSelect函数中,你需要将元素传递给createSelect函数。
function createSelect(element, data) {
for(i = 0; i < data.length; i++) {
var select = $('<select></select');
//Use element
element.parent().append(select);
}
}
$(document).ready(function () {
$('.note').click(function () {
var element = $(this); //Store this reference
$.ajax({
success: function(data) {
createSelect(element, data); //pass the element
}
});
};
});
});