[英]Replace next occurrence of a string
我在玩耍,试图为将来在我有想法的项目中使用某些东西。 但是,我似乎无法使其正常运行。 我确信这不是最好的方法,但这是我能想到的唯一方法。 因此,这可能就是为什么我也无法使其正常工作的原因。
问题:问题是该函数不能替换多个现有单词的字符串中出现的下一个单词。 相反,它返回到字符串中第一个相同的单词。 我从这里尝试了一些RegExp
解决方案,但未能使其正常工作。
应该做什么? 只是循环浏览每个单词并突出显示它一会儿。 它应该使用generateTime
数组为每个单词设置不同的循环时间。 稍后,最有可能是一个JSON
对象。
这只是JS代码:
var // ->
textElement = $( '.text' ),
contentReplace = textElement.text().replace( /[^\w ]/g, '' ).split( /\s+/ ),
generateTime = [],
inc = 0,
interval = false;
// Generate random time
for ( var i = 0; i <= contentReplace.length; i++ ) {
generateTime.push( Math.random() * (1 - 0.1) + 0.1 );
}
// Interval for looping trough words
var ticker = setInterval(function () {
if ( inc == ( generateTime.length - 2 ) ) {
clearTimeout( ticker );
}
if ( ! interval ) {
setTimeout(function () {
textElement
.html( textElement.text().replace(contentReplace[inc], '<span>' + contentReplace[inc] + '</span>') );
inc++;
interval = false;
}, generateTime[inc] * 1000);
}
interval = true;
}, 500);
如果有人可以帮助我解决这个问题,
您需要跟踪最后匹配的索引。 尝试这个:
var // -> textElement = $( '.text' ), contentReplace = textElement.text().replace( /[^\\w ]/g, '' ).split( /\\s+/ ), generateTime = [], inc = 0, interval = false; lastIndex = 0; // Generate random time for ( var i = 0; i <= contentReplace.length; i++ ) { generateTime.push( Math.random() * (1 - 0.1) + 0.1 ); } // Interval for looping trough words var ticker = setInterval(function () { if ( inc == ( generateTime.length - 2 ) ) { clearTimeout( ticker ); } if ( ! interval ) { setTimeout(function () { var text = textElement.text(); textElement .html( text.substr( 0, lastIndex ) + text.substr( lastIndex, text.length ).replace( contentReplace[inc], function ( match, index ) { lastIndex = lastIndex + index + match.length; return '<span>' + contentReplace[inc] + '</span>' })); inc++; interval = false; }, generateTime[inc] * 1000); } interval = true; }, 500);
body { font-family: "Helvetica"; padding: 25px; text-align: center; } span { background-color: #c22; color: #fefefe; padding: 8px; border-radius: 3px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="text">Lets try to make it work. Try, then try again and once again - try.</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.