[英]Count number of times a string of text appears on a page with Javascript
I have a view in an MVC web application that produces and presents a list of countries and the name of their capital cities. 我在MVC Web应用程序中有一个视图,该应用程序会生成并显示国家/地区列表及其首都名称。 Whenever the view loads, if the results presented to the user contain the words 'Australia' one or more times, then I want a message to appear at the bottom of the screen that says 'Australia is included in the results'.
无论何时加载视图,如果呈现给用户的结果包含一个或多个单词“ Australia”,那么我希望在屏幕底部显示一条消息,指出“ Australia包含在结果中”。 I have used the following script, but the message appears whether or not Australia is in the results.
我使用了以下脚本,但无论结果中是否包含澳大利亚,都会出现消息。 Does anyone have any suggestions?
有没有人有什么建议?
<script type='text/javascript'>
if (
(
document.documentElement.textContent || document.documentElement.innerText
).indexOf('Australia') > -1
) {
alert("Australia is included in the results");
}
</script>
Thanks in advance 提前致谢
I think only this condition might suffice: 我认为只有这种情况才能满足:
if (document.documentElement.innerText.indexOf('Australia') > -1) {
alert("Australia is included in the results");
}
Your code looks sensible, so I suspect that the problem is that it is finding the string "Australia" in the code its self ! 您的代码看起来很明智,因此我怀疑问题是它在代码自身中找到了字符串“ Australia”!
Try putting this script outside of the page contents (in a separate .js file) and see if the problem persists. 尝试将此脚本放在页面内容之外(在单独的.js文件中),看看问题是否仍然存在。
Maybe ;-) 也许 ;-)
This is actually an answer for your follow up question about using HTML instead of an alert (I can't post comments, so had to do it this way, sorry.) 这实际上是您关于使用HTML而不是警报的后续问题的答案(我无法发表评论,所以不得不这样做,对不起。)
What you want is document.getElementById("element_ID").innerHTML = "whatever";
您想要的是
document.getElementById("element_ID").innerHTML = "whatever";
See here: http://jsfiddle.net/UVU8w/ 看到这里: http : //jsfiddle.net/UVU8w/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.