【问题标题】:jQuery .attr() function within loop循环内的 jQuery .attr() 函数
【发布时间】:2017-10-24 14:57:04
【问题描述】:

我正在尝试通过 jQuery 动态替换属性 - 在我的 for 循环中,我正在使用 .attr()-function,它工作正常,但 JSLint 抱怨:

不要在循环中创建函数。

我知道我可以在 JSLint 配置中禁用这些特定测试,但我想了解如何通过在循环外放置一个相应的函数并在使用 .attr() 时相应地调用它来解决这个问题

旧逻辑

for (var i = currentRowIndex + 1; i <= oldIndex; i++) {

  [...]

  selectorName.attr( 'name', function( index, name ) {
    return name.replace( /\d+/g, newIndex );
  } );
}

所需的逻辑

var replaceAttr = function( index, attr ) {
  return attr.replace( /\d+/g, index );
};

for (var i = currentRowIndex + 1; i <= oldIndex; i++) {

  [...]

  selectorName.attr( 'name', replaceAttr( function( newIndex, name ) );
}

问题

虽然第一个代码运行良好并且正确地定位/传递了名称属性,但第二个代码只是替换了一个空属性。对 JS 还是很陌生,我不知道如何解决这个问题......

  • 关闭有问题吗?
  • 如何传递/设置目标以便识别它而不仅仅是一个字符串?
  • 是否要创建一个包含 .attr() 步骤帮助的“主”功能?

期待了解这个:)

提前致谢!

【问题讨论】:

  • 创建id为数字,然后在循环中定义选择器为$('#id'+ i).attr('attribute', 'value;);
  • function( newIndex, 'name' ) 这里name 作为字符串而不是变量参数
  • @ThisGuyHasTwoThumbs 你这是什么意思?我的 ID 很好,选择器可以工作,我只是没有发布完整的代码,但如果需要可以添加......
  • 可能不需要for() 循环。显示更多代码上下文以及如何定义 selectorName
  • 问题是,你没有显示selectorName 函数的代码

标签: javascript jquery jslint


【解决方案1】:

您在外部化函数时犯了一个小错误。对attr 的调用可以接受一个函数,但这意味着你的 函数需要返回一个函数——这通常被称为闭包。

var replaceAttr = function(newIndex){
 return  function( index, attr ) {
   return attr.replace( /\d+/g, newIndex );
 }
}

for (var i = currentRowIndex + 1; i <= oldIndex; i++) {

  [...]

  selectorName.attr( 'name', replaceAttr(newIndex) );
}

【讨论】:

  • 太棒了!!谢谢,那就得在闭包上做更多的工作......!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-06
  • 2015-05-11
  • 1970-01-01
  • 1970-01-01
  • 2016-12-16
相关资源
最近更新 更多