【问题标题】:jQuery - I'm having trouble looping through elements by class and executing a function each timejQuery - 我无法按类循环遍历元素并每次执行一个函数
【发布时间】:2022-07-07 21:56:03
【问题描述】:

这是我的 jsfiddle:

https://jsfiddle.net/Lyt9o6b2/

HTML:

 <textarea class="TextArea" id="TextArea1">Text in block 1</textarea>
 <div class="PrintHelp" id="TextArea1PrintHelp"></div>
 <br/><br/><br/><br/><br/>
 <textarea class="TextArea" id="TextArea2">Text in block 2</textarea>
 <div class="PrintHelp" id="TextArea2PrintHelp"></div>

jQuery:

 function copy_to_print_helper(TextAreaID, PrintHelpID){
     $('#' + TextAreaID).text($('#' + PrintHelpID).val());
   }
   
 $('.TextArea').each(function(){
 copy_to_print_helper(this, this + 'PrintHelp')
 })

在 PageLoad 上,我想遍历类“TextArea”的所有 textarea 元素,然后执行 copy_to_print_helper() 函数将该 textarea 的文本复制到相应的 div 中。我对 jQuery 的经验很少,但我想我离得不远了——知道我错过了什么吗?

【问题讨论】:

  • 是否应该获取元素的ID?

标签: jquery


【解决方案1】:

主要问题在于您在 jQuery 事件处理程序中使用 this。这将包含对 Element 对象的引用。但是,在copy_to_print_helper 中,您希望此值是一个字符串,可以附加到元素的id 以形成选择器,但事实并非如此。您需要访问该对象的 id 属性才能使其工作 - 但即使这样,也有更好的方法。

使用对象本身的this引用来获取textarea的属性,也可以在DOM中找到相关的元素。这完全避免了您在运行时动态定位的任何增量 id 属性的需要,从而使 HTML 和 JS 代码更加简单和可靠:

function copy_to_print_helper(textarea) {
  $(textarea).next('.PrintHelp').text(textarea.value);
}

$('.TextArea').each(function() {
  copy_to_print_helper(this)
})
.PrintHelp {
  margin-bottom: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<textarea class="TextArea">Text in block 1</textarea>
<div class="PrintHelp"></div>

<textarea class="TextArea">Text in block 2</textarea>
<div class="PrintHelp"></div>

更进一步,可以通过向text() 提供一个函数来使逻辑更加简洁,该函数使用对集合中每个元素的隐式循环返回要在每个div 中显示的值:

$('.print-help').text(function() {
  return $(this).prev('.textarea').val();
});
.print-help {
  margin-bottom: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<textarea class="textarea">Text in block 1</textarea>
<div class="print-help"></div>

<textarea class="textarea">Text in block 2</textarea>
<div class="print-help"></div>

【讨论】:

    猜你喜欢
    • 2018-06-29
    • 2020-12-04
    • 1970-01-01
    • 2020-12-22
    • 1970-01-01
    • 2011-07-14
    • 2012-05-30
    • 2011-03-09
    • 2013-06-22
    相关资源
    最近更新 更多