我正在努力更改选择的下拉菜单。为此,我使用 jquery、ajax 和 json。
function ChooseGroupScript() {
$.getJSON('edit_scripts.php', {group:$('#group').val()}, function(data) {
var select = $('#subject');
var options = select.attr('options');
$('option', select).remove();
$.each(data, function(index, array) {
options[options.length] = new Option(array['subject']);
});
});
}
$(document).ready(function() {
ChooseGroupScript();
$('#group').change(function() {
ChooseGroupScript();
});
});
我检查了控制台:我收到这样的错误:
Jquery type error on cannot read property 'length' of undefined
这是我的 PHP:
if(isset($_GET['group'])){
$currentscript = $clients->curr_group_content($_GET['group']);
$scriptscount = sizeof($currentscript);
for($i=0;$i<$scriptscount;$i++){
$subject = $currentscript[$i]['subject'];
}
}
echo json_encode($subject);
HTML:
<form>
<select name="group" id="group">
<option>comming from database.....</option>
</select>
<select name="subject" id="subject">
</select>
</form>
最佳答案
options 不是 select 元素的属性。您可能只是想直接将新选项添加到元素中:
var select = $('#subject');
// remove this: var options = select.attr('options');
$('option', select).remove(); // or select.empty() to clean it out
$.each(data, function(index, array) {
select.append(new Option(array['subject']));
});
关于javascript - Jquery类型错误无法读取未定义的属性 'length',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18906334/