[英]JavaScript function default parameter value
I'm trying to set a default value for a function parameter, that will query my server for an initial value. 我正在尝试为功能参数设置默认值,该默认值将查询服务器的初始值。
The end goal is i will be able to click on one of the list items I create to retrieve and create a new list. 最终目标是,我将能够单击我创建的列表项之一来检索和创建新列表。
<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>
If I manually set jobid to 0(commented out in the code above) everything works perfectly. 如果我手动将jobid设置为0(在上面的代码中注释),则一切正常。 If i try to set it in the function parameter list i get this in my console.log: jobid: function(e,t){return new w.fn.init(e,t)}
如果我尝试在功能参数列表中进行设置,则会在console.log中得到它:jobid:function(e,t){返回新的w.fn.init(e,t)}
When jQuery calls the callback to $(function(x) { ... })
, the argument is the jQuery object itself, therefore having a default value is never going to be needed 当jQuery调用
$(function(x) { ... })
的回调时,参数是jQuery对象本身,因此不再需要使用默认值
so, you'll want to do this instead 因此,您将改为执行此操作
$(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();
});
alternatively, using your original code, you could of course test for the case where typeof jobid is a function, and set it to 0
instead ... ie 另外,使用您的原始代码,您当然可以测试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>");
});
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.