【发布时间】:2014-12-13 19:31:56
【问题描述】:
我正在做我的第一个 javascript 应用程序,我注意到它只适用于 firefox(我无法测试 IE)。 我创建这个软件只是为了做一些练习,简单地说,它允许在给定文本中搜索给定单词,并在 div 块上呈现,原始文本突出显示搜索的单词(如果存在)并告诉找到该词的次数。
变量string是要搜索的文本,变量target是要搜索的词,变量result 是存储在 string 中的搜索结果的位置。
我遇到的问题是,虽然在 Firefox 中代码可以完美地找到文本中每次存在的单词,但在其他浏览器中(基于 webkit?)它只能找到一次单词。 em>
这是 JavaScript 代码:
function wordFinder() {
'use strict';
var string = document.getElementById('paste').value,
target = document.getElementById('target').value,
result = string.match(target, 'g'),
marked = string.replace(target, '<span class="found">' + target + '</span>', 'g');
if (result === null) {
document.getElementById('result').innerHTML = 'Your word was not found in the content';
document.getElementById('string').innerHTML = '<h2 align="center">No results to display</h2>';
} else {
document.getElementById('result').innerHTML = ('The word ' + target + ' was found ' + result.length + ' times.');
document.getElementById('string').innerHTML = marked;
}
}
这是 HTML:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
<script src="script.js" type="text/javascript" language="javascript"></script>
</head>
<body>
<h2>Word finder</h2>
<form name="finder" action="wordFinder" method="post">
Paste the text you want to search within:<br>
<textarea name="text" rows="10" cols="100" id="paste"></textarea><br>
Paste the word you want to search:<br>
<input name="search" type="text" id="target"/>
<br><button type="button" onclick="wordFinder()">Search.</button>
</form>
<h4 id="result"></h4>
<div id="style" class="layout"><p id="string">Results will appear here</p></div>
</body>
</html>
提前感谢您的帮助
【问题讨论】:
标签: javascript google-chrome firefox safari opera