繁体   English   中英

jQuery - 我无法按类循环遍历元素并每次执行一个函数

[英]jQuery - I'm having trouble looping through elements by class and executing a function each time

这是我的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 的经验很少,但我猜我离我不远了——知道我错过了什么吗?

主要问题是您在 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: 50px; }
 <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: 50px; }
 <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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM