使用 jQuery 遍历 HTML 元素以检索<textarea>内容



在我的项目中,我有一个表,每行都有一个单元格,定义如下:

<td onclick='openNotes()'> <div class='notes-popup' id='notesForm'><form class='notes-container'> 
<textarea name='reqnotes'>123</textarea></form></div></td>

如何使用jQuery遍历此结构并获取文本区域内的文本?

选择具有name属性的文本区域,并使用val()方法获取值。

$(function() {
var reqnotes = $('textarea[name ="reqnotes"]').val();
console.log('Value of reqnotes : ' + reqnotes);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<td onclick='openNotes()'> <div class='notes-popup' id='notesForm'><form class='notes-container'> 
<textarea name='reqnotes'>123</textarea></form></div></td>

  • 避免使用内联JS。这很难调试。JS应该放在一个地方,而不是分散在HTML文件中。请改用类名数据-*属性

使用jQuery和纯JavaScript的示例:

function openNotes() {
const $textarea = $(this).find('[name="reqnotes"]');
console.log( $textarea.val() )
};

$(".js-openNotes").on("click", openNotes);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<!-- inline JS is bad for health and debugging. Use .addEventListener() instead -->
<td class="js-openNotes">
<div class='notes-popup' id='notesForm'>
<form class='notes-container'>
<textarea name='reqnotes'>123</textarea>
</form>
</div>
</td>
</tr>
</table>

或者不带jQuery:

const openNotes = (ev) => {
const textarea = ev.currentTarget.querySelector('[name="reqnotes"]');
console.log( textarea.value )
};

const ELS_openNotes = document.querySelectorAll(".js-openNotes");
ELS_openNotes.forEach(el => el.addEventListener("click", openNotes));
<table>
<tr>
<!-- inline JS is bad for health and debugging. Use .addEventListener() instead -->
<td class="js-openNotes">
<div class='notes-popup' id='notesForm'>
<form class='notes-container'>
<textarea name='reqnotes'>123</textarea>
</form>
</div>
</td>
</tr>
</table>

最新更新