Javascript 变量值作为 html 类名中的数字

标签 javascript html variables

我想将变量“i”放入此代码中:

do {
$('.dot:nth-child(1)').click(function(){
  $('.inside').animate({
    'width' : (i*width)+'%'
  }, 500);
});    
i++;
}
while (i <= number);

像这样 - 但它不起作用:

do {
$('.dot:nth-child('+ i +')').click(function(){
  $('.inside').animate({
    'width' : (i*width)+'%'
  }, 500);
});    
i++;
}
while (i <= number);

最佳答案

这是经典的闭包问题:传递给 click 的函数具有对 i 变量的持久引用,而不是 >创建函数时的副本。因此,当点击发生时(循环结束后),所有点击最终都会使用i的值

通常的解决方案是使用构建器函数:

do {
  $('.dot:nth-child('+ i +')').click(buildHandler(i));    
  i++;
}
while (i <= number);

function buildHandler(index) {
  return function(){
    $('.inside').animate({
      'width' : (index*width)+'%'
    }, 500);
  };
}
<小时/>

也就是说,在这种情况下,您不需要为每个元素使用不同的处理函数;相反,只需使用一个处理函数来检查它正在处​​理哪个子进程:

$('.dot').click(function(){
  var index = $(this).index();
  $('.inside').animate({
    'width' : (index*width)+'%'
  }, 500);
});

更多:index

关于Javascript 变量值作为 html 类名中的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29378993/

相关文章:

html - 当浏览器窗口太小时,将 div 向左截断

javascript - 设计一个专业的网站

java - Java 中的浅拷贝整数

excel - 在VBA函数中计算二变量函数的值

javascript - 如何在不使用 refs 和手动修改 DOM 的情况下使用 React 传单向 map 添加图例?

javascript - devtools 中奇怪的 JS 脚本

javascript - 我无法在 restify( Node JS)中从 req.params 读取参数值

javascript - 查找将按钮设置为焦点的脚本

html - 使用 CSS 创建全 Angular 背景色

C# 标志问题