我正在尝试为函数参数设置一个默认值,该参数将查询服务器的初始值。
最终目标是我将能够单击我创建的列表项之一来检索并创建新列表。
<script type="text/javascript">
$(function getJobs(jobid=0) {
{#jobid = 0;#}
console.log("jobid: " + jobid);
let query = {id: jobid};
console.log(query);
$.getJSON("{% url 'website:get-jobs' %}", query, function (data) {
console.log("getjson");
$.each(data, function (key, value) {
console.log(key + " - " + value);
$('#jobs-list').append("<li id='" + key + "'" + "href='#'" + "onclick=getJobs(key)" + ">" + value + "</li>");
});
});
})
</script>
如果我手动将jobid设置为0(在上面的代码中注释),则一切正常。如果我尝试在功能参数列表中进行设置,请在console.log中获取: jobid:function(e,t){返回新的w.fn.init(e,t)}
答案 0 :(得分:1)
当jQuery调用$(function(x) { ... })
的回调时,参数是jQuery对象本身,因此永远不需要默认值
所以,您将改为这样做
$(function() {
function getJobs(jobid = 0) {
console.log("jobid: " + jobid);
let query = {id: jobid};
console.log(query);
$.getJSON("{% url 'website:get-jobs' %}", query, function (data) {
console.log("getjson");
$.each(data, function (key, value) {
console.log(key + " - " + value);
$('#jobs-list').append("<li id='" + key + "'" + "href='#'" + "onclick=getJobs(key)" + ">" + value + "</li>");
});
});
}
getJobs();
});
或者,使用您的原始代码,您当然可以测试typeof jobid是函数的情况,然后将其设置为0
……即
$(function getJobs(jobid) {
if (typeof jobid === 'function') {
jobid = 0;
}
console.log("jobid: " + jobid);
let query = {id: jobid};
console.log(query);
$.getJSON("{% url 'website:get-jobs' %}", query, function (data) {
console.log("getjson");
$.each(data, function (key, value) {
console.log(key + " - " + value);
$('#jobs-list').append("<li id='" + key + "'" + "href='#'" + "onclick=getJobs(key)" + ">" + value + "</li>");
});
});
});