我正在做我的第一個JavaScript應用程序,我注意到,它只適用於Firefox(我無法測試IE瀏覽器)。 我創建這個軟件只是爲了做一些練習,用幾句話就可以搜索給定文本中的給定單詞,並在div塊上呈現突出搜索單詞的原始文本(如果存在)並且還告訴這個詞被發現的次數。JavaScript兼容性鉻,Safari瀏覽器和歌劇搜索字符串
變量串就是搜索將要完成的文本中,變量目標是搜索詞,變量結果就是串內的搜索的結果存儲。
我遇到的問題是,儘管在Firefox中,代碼能夠完美地發現文本中每個單詞存在的時間,在其他瀏覽器(基於webkit?)中,它只能找到一次該單詞。
這裏的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>
感謝您的幫助
嗨,謝謝,現在有用。我只有一個問題(因爲這個概念對我來說還不是很清楚)。 「找到」類的範圍僅適用於第一個單詞,其餘單元不標記。 :) – 2014-10-21 18:56:50