[英]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.