我设置了一个全局变量$category_list,它是一个类别名称数组。
在页脚我有:
<?php if ( isset($category_list) ): ?>
<script type="text/javascript">
var wordlist = [
<?php foreach ($category_list as $row) { echo '"' . $row->name . '", '; } ?>
];
</script>
<?php endif ?>
我有一个外部的.js文件,代码如下:
jQuery( ".cats" ).autocomplete({
source: function(req, responseFn) {
var matches = new Array();
var needle = req.term.toLowerCase();
var len = wordlist.length;
for(i = 0; i < len; ++i)
{
var haystack = wordlist[i].toLowerCase();
if(haystack.indexOf(needle) == 0 ||
haystack.indexOf(" " + needle) != -1)
{
matches.push(wordlist[i]);
}
}
responseFn( matches );
}
});
在IE8中出现错误,因此下拉菜单无法工作:wordlist[...] is null or not an object
不知道如何解决这个问题,类别名称的下拉列表在ie9, Firefox和Chrome中工作得很好,但在IE8中却不能,影响了大约50%的IE用户。我正在使用Codeigniter框架。我试着在外部文件之前加载页脚脚本,但没有乐趣。
感谢您的帮助<3
IE8不喜欢在数组字面量定义中尾随,
。你必须重构你的代码,不留下一个。
<?php
$rows = array();
foreach ($category_list as $row) { $rows[] = '"' . $row->name . '"'; }
echo implode(',', $rows);
?>
或
var wordlist = <?php
$rows = array();
foreach ($category_list as $row) { $rows[] = '"' . $row->name . '"'; }
echo json_encode($rows);
?>;