var funcs = [];
// let's create 3 functions
for (var i = 0; i < 3; i++) {
// and store them in funcs
funcs[i] = function() {
// each should log its value.
console.log("My value: " + i);
};
}
for (var j = 0; j < 3; j++) {
// and now let's run each one to see
funcs[j]();
}Run Code Online (Sandbox Code Playgroud)
它输出这个:
我的价值:3
我的价值:3
我的价值:3
而我希望它输出:
我的价值:0
我的价值:1
我的价值:2
使用事件侦听器导致运行函数的延迟时,会出现同样的问题:
var buttons = document.getElementsByTagName("button");
// let's create 3 …Run Code Online (Sandbox Code Playgroud)有没有办法将更多数据传递给jQuery中的回调函数?
我有两个函数,我希望回调$.post,例如,传递AJAX调用的结果数据,以及一些自定义参数
function clicked() {
var myDiv = $("#my-div");
// ERROR: Says data not defined
$.post("someurl.php",someData,doSomething(data, myDiv),"json");
// ERROR: Would pass in myDiv as curData (wrong)
$.post("someurl.php",someData,doSomething(data, myDiv),"json");
}
function doSomething(curData, curDiv) {
}
Run Code Online (Sandbox Code Playgroud)
我希望能够将自己的参数传递给回调,以及从AJAX调用返回的结果.
似乎无法弄清楚这里发生了什么.
<div id="navigation">
<ul id="navList">
<li class="navItem"><a href="http://www.jacobsmits.com/placeholderRX.html">Discover</a></li>
<li class="navItem"><a href="http://www.jacobsmits.com/placeholderRX/documentation.html">Documentation</a></li>
<li class="navItem"><a href="http://www.jacobsmits.com/placeholderRX/download.html">Download</a></li>
<li class="navItem"><a href="http://www.jacobsmits.com/placeholderRX/donate.html">Donate</a></li>
</ul>
<script type="text/javascript">
$('.navItem').each(function() {
$link = $(this).children('a');
$link.hover(
function() {
$link.css('width', '224px');
},
function() {
$link.css('width', '192px');
}
)
});
</script>
</div>
Run Code Online (Sandbox Code Playgroud)
它应该为每个链接执行它,而不是只更改最后一个链接,无论哪个链接正在悬停.