简体   繁体   中英

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

Here is my 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')
 })

On PageLoad, I want to loop through all of my textarea elements of class 'TextArea' and then execute the copy_to_print_helper() function to copy that textarea's text into the corresponding div. I have very little experience with jQuery but I'm guessing I'm not far off - any idea what I'm missing?

The main issue is with your use of this in the jQuery event handler. That will hold a reference to the Element object. However in the copy_to_print_helper you expect this value to be a string which can be appended to the id of the element to form a selector, which is not the case. You would need to access the id property of the object for that to work - but even then there's a better approach.

Use the this reference of the object itself to get the properties of the textarea , and also to find the related element in the DOM. This completely avoids the need for any incremental id attributes which you dynamically target at runtime, making the HTML and JS code much more simple and reliable:

 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>

Taking this a step further, the logic can be made more succinct by providing a function to text() which returns the value to be displayed in each div using an implicit loop over every element in the collection:

 $('.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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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