我有下面的代码的HTML文件工作,我与它的问题:的JavaScript/jQuery的复制文本的亮点将不会在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/,但不工作在我的浏览器中。
我做了什么?从的jsfiddle
将代码粘贴到HTML我的文件(CSS,javascript和 把它们放在HTML标签之间)
添加链接到jQuery库
当我打电话从文件本地主机(我使用XAMMP)使其正常显示,但是当我点击链接,亮点重复,没有任何反应:(在
下发展控制台r工具(Chrome)不显示任何内容(没有错误,没有信息 - 只是空白)。
我在做什么错了?
把你的脚本,在''
标签的结束或(如在的jsfiddle)在'OnDomReady'事件,它应该工作。 – Scott如果@斯科特的权利,我相信他是,问题是脚本在页面上执行的顺序。你必须想象当你看到$(..)时,它实际上是从页面获取项目,如果它在页面完成之前运行,它什么也找不到,因此什么也不做(如果没有找到项目,jQuery不执行任何操作)。 – Neil
在这种情况下使用jQuery的'$(document).ready(function(){/ *执行你的代码* /})'可能是个好主意。 – tommyO