を動作しません、重複:のJavaScript/jQueryのテキストのハイライトは、私は以下のコードでHTMLファイルを持っていると私はそれに問題があるHTMLファイルに
<html>
<head>
<title>TITLE</title>
<style type="text/css">
span.duplicate { background: yellow; }
</style>
<script
src="https://code.jquery.com/jquery-3.2.1.js"
integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
crossorigin="anonymous">
</script>
<script>
var text = $('p').text(),
words = text.split(' '),
sortedWords = words.slice(0).sort(),
duplicateWords = [],
sentences = text.split('.'),
sortedSentences = sentences.slice(0).sort(),
duplicateSentences = [];
for (var i=0; i<sortedWords.length-1; i++) {
if (sortedWords[i+1] == sortedWords[i]) {
duplicateWords.push(sortedWords[i]);
}
}
duplicateWords = $.unique(duplicateWords);
for (var i=0; i<sortedSentences.length-1; i++) {
if (sortedSentences[i+1] == sortedSentences[i]) {
duplicateSentences.push(sortedSentences[i]);
}
}
duplicateSentences = $.unique(duplicateSentences);
$('a.words').click(function(){
var highlighted = $.map(words, function(word){
if ($.inArray(word, duplicateWords) > -1)
return '<span class="duplicate">' + word + '</span>';
else return word;
});
$('p').html(highlighted.join(' '));
return false;
});
$('a.sentences').click(function(){
var highlighted = $.map(sentences, function(sentence){
if ($.inArray(sentence, duplicateSentences) > -1)
return '<span class="duplicate">' + sentence + '</span>';
else return sentence;
});
$('p').html(highlighted.join('.'));
return false;
});
</script>
</head>
<body>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam. Quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Ut enim ad minim veniam. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum
</p>
<hr />
<a class="words" href="#">Find duplicate words</a>
|
<a class="sentences" href="#">Find duplicate sentences</a>
</body>
</html>
それは次のように動作するはずです:http://jsfiddle.net/SaQAs/1/が、動作していません私のブラウザで。
私は何をしましたか? HTML私のファイルにjsfiddleから
貼り付けコード私はからファイルを呼び出すとjQueryライブラリ
に
追加リンクを(CSSでは、JavaScriptと は、HTMLタグの間に置きます) localhost(私はXAMMPを使用しています)正しく表示されますが、ハイライトの重複のためのリンクをクリックしても何も起こりません:(
コンソール開発中rツール(Chrome)は何も表示しません(エラーはなく、情報はありません)。
私は間違っていますか?
は(JSFiddleのように) ''
タグの最後にスクリプトを置くか、 'OnDomReady'イベントで、それが動作するはずです。 – Scott@ Scottの権利は、私は彼がいると信じている場合、問題はページ上のあなたのスクリプトの実行の順序です。 $(..)が表示されたら、実際にページからアイテムを取得しています。ページが完成する前に実行されていれば、何も見つからないので何もしません(jQueryはアイテムが見つからなければ何もしません)。 – Neil
この状況では、jQueryの '$(document).ready(function(){/ *あなたのコード* /}を実行してください。 – tommyO