我想允许用户输入搜索字符串,并且我想返回找到该搜索项的次数。如果我将搜索值硬编码到“包含”方法中,我就可以让它工作,但是一旦我将搜索值存储到变量中,它就不再起作用。
HTML:
<div class="myTest">this</div>
<div class="myTest">this</div>
<div class="myTest">that</div>
<div class="myTest">that</div>
<div class="myTest">this</div>
<div id="howMany"></div>
JAVASCRIPT:
$(function() {
var myVal= "that";
var existingList = $("div:contains(myVal) + .myTest").length;
$("div[id*='howMany']").html(existingList);
})
最佳答案
您的代码中存在一些错误:
-
jQuery 选择器中的
+
doesn't do你认为它会做什么- 您在选择器中包含字符串
myVal
,而不是myVal
的值 - 使用
#
查找具有给定id的元素
您可以使用搜索
var existingList = $('div.myTest:contains("'+myVal+'")').length;
但这不适用于包含双引号的字符串。对于任何类型的字符串,我宁愿建议
var existingList = $('div.myTest').filter(function(){
return $(this).text().indexOf(myVal)>=0;
}).length;
要发出找到的结果数,请使用
$("#howMany").html(existingList);
关于javascript - 当搜索值是动态时,如何获取包含特定文本的 div 的计数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13081989/