【发布时间】:2026-02-05 15:45:02
【问题描述】:
如何获取所有跨度文本并匹配 jQuery 上的文本输入?
这是我的 HTML 代码。具有数据和跨度的表,其中包含文本 MEW、MEWL 和 MOWL:
我的 jQuery 代码尝试。它总是提醒false:
$(function() {
$('#btn').on('click', function() {
if ($('#txt').val == $('.answer').text()) {
alert("true");
} else {
alert("false");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<table>
<tr>
<td><span class="answer">MEW</span></td>
<td><span class="answer">MEWL</span></td>
<td><span class="answer">MOWL</span></td>
</tr>
</table>
<input type="text" id="txt" />
<input type="button" id="btn" value="Click" />
我想检查跨度的文本是否与输入值匹配,例如:我将输入 MEW 系统应该警报 true,因为跨度的文本中存在 MEW。
【问题讨论】:
-
可能是因为您的
txt属性不是class,而是id。 -
嗨,把你的跨度答案放在
-
很抱歉,这只是一个错字。但即使我改变了它也不起作用。
-
$(function(){ $('#btn').on('click', function(){ $('table').find('td').each(function( ){ var ans = $(this).find('span').text(); if($('#txt').val == ans){ alert("true"); } else{ alert("假"); } }); }); });
-
val是一个函数,所以使用val()
标签: jquery