2014-10-18 17 views
1

我正在做我的第一個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> 

感謝您的幫助

回答

0

這條線被區別對待:

result = string.match(target, 'g'), 

請注意,string.match需要一個RegExp參數(請參閱ES5.1 spec)。您傳遞了兩個參數,這意味着第一個被視爲RegExp,這意味着它不會給你一個全局匹配,除非target類似於/foo/g。您可以創建RegExp反對自己,使之在全球範圍匹配:

result = string.match(new RegExp(target, 'g')), 

fiddle。我測試了Opera 12(presto),Opera 26,IE11和Chrome 40,它們都表現相同的方式,給你的原始代碼一個匹配,只有Firefox的行爲不同 - 看似違反了EcmaScript 5.1規範。

+0

嗨,謝謝,現在有用。我只有一個問題(因爲這個概念對我來說還不是很清楚)。 「找到」類的範圍僅適用於第一個單詞,其餘單元不標記。 :) – 2014-10-21 18:56:50