如何在jQuery上获取所有跨文本并与文本输入相匹配?这是我的HTML代码。包含数据和包含文本MEW、MEWL和MOWL的span的表
我的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" />
我想检查span的文本是否与输入值相匹配,例如:我将输入MEW系统应该警告true,因为MEW存在于spans的文本中。
发布于 2018-07-11 09:09:51
$(function(){
$('#btn').on('click', function(){
$('table').find('td').each(function(){
var ans = $(this).find('span').text();
if($('#txt').val() == ans){
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" />
发布于 2018-07-11 08:24:20
下面的行将为您提供span .answer中的文本数组。$('.answer').toArray().map(x => $(x).text())
.includes()将检查数组是否包含该值。它将返回true或false。
你可以按下面的方式检查。
$(function() {
$('#btn').on('click', function() {
if ($('.answer').toArray().map(x => $(x).text()).includes($('#txt').val())) {
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" />
发布于 2018-07-11 08:24:39
首先,$('#txt').val应该是$('#txt').val(),因为它是一种方法。阅读更多关于 here的信息。
您需要对all .answer元素进行迭代,并检查值是否匹配。
$('#btn').on('click', function(){
var found = false;
$('.answer').each(function(index, elem){
if($(elem).text().toLowerCase().trim() == $('#txt').val().toLowerCase().trim()) {
found = true;
return false;
}
});
alert(found);
});
$(function(){
$('#btn').on('click', function(){
var found = false;
$('.answer').each(function(index, elem){
if($(elem).text().toLowerCase().trim() == $('#txt').val().toLowerCase().trim()) {
found = true;
return false;
}
});
alert(found);
});
});<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/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" />
https://stackoverflow.com/questions/51280224
复制相似问题