使用 Jquery 将子字符串替换为段落中的 html 元素,而不会弄乱出现的事件

Replace substrings by html elements inside a paragraph without messing with occurrences using Jquery

本文关键字:会弄 事件 元素 html Jquery 字符串 替换 段落中 使用      更新时间:2023-09-26

我的目的是改变段落中的每个单词的颜色,平滑和一个接一个。

它可以工作,但子字符串的出现使其崩溃。我不太擅长javascript,但这就是我到目前为止所做的:

// GET WORDS LIST
var pText = $('p').text(); //Get the text of the concerned element
var pArray = pText.split(/'s/g); //Transform the string in an array
//Put values in a clean new array without spaces
var pClean = new Array();
var j = 0; 
for (var i = 0; i < pArray.length; i++) {
  if(pArray[i] != ''){
    pClean[j] = pArray[i];
    j++;
  }
}
var pArray = []; //Delete the old one

//WRAP AND REPLACE WORDS
var i = 0;
setInterval( function () {
  //stop the loop
  if(pClean[i] == ''){
  // I don't really ge how to use clearInterval for stopping the loop.
  }
  //replace words
  if($('p').text().indexOf(pClean[i])){
    $('p:contains("'+pClean[i]+'")').html(function(_, html) {
      var replacement = '<span class="read">'+pClean[i]+'</span>';
      return  html.replace(pClean[i], replacement);
    });
    $('p .read:last').addClass('hlight'); //highlight the last
  }
  i++;
}, 300);

这是jsfiddle。

这一定是更好的方法...谢谢你的时间!

编辑-----

我应用了经过验证的答案的代码,它运行得很好,但我也尝试在追加函数中添加异常,但没有任何成功。它似乎没有检测到这个变量。

var words = $("p").text().split(" ");
$("p").empty();
$.each(words, function(i, v) {
    if(this == '4.'){
        $(p).append($('<br><span>'+v+'</span>'));
    }
    else {
        $(p).append($("<span>").text(v)).append(" ");
    }
});
//WRAP AND REPLACE WORDS
var i = 0;
setInterval( function () {
    //stop the loop
    if($('p :not(.read):first').length == 0){
    }
     $('p :not(.read):first').addClass("read");
    //$("p .read").removeClass("hlight");
    $("p .read:last").addClass("hlight");
}, 500);

你有什么想法吗?谢谢

如果你这样做,你从每个单词周围的跨度开始,然后你可以一个接一个地添加类。

var words = $("p").text().split(" ");
$("p").empty();
$.each(words, function(i, v) {
    $("p").append($("<span>").text(v)).append(" ");
});
//WRAP AND REPLACE WORDS
var i = 0;
setInterval( function () {
    //stop the loop
    if($('p :not(.read):first').length == 0){
	}
     $('p :not(.read):first').addClass("read");
    //$("p .read").removeClass("hlight");
    $("p .read:last").addClass("hlight");
}, 500);
p{
  color: black;
  width: 200px;
  margin: 100px auto 0 auto;
}
p .read{
    color: black;
    transition: color 1s ease-in-out 0.1s;
    -webkit-transition: color 1s ease-in-out 0.1s;
}
p .read.hlight{
    color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit.  
    Vestibulum dignissim, nisl nec laoreet hendrerit, tellus eros 
    tristique tortor, eu commodo nunc sem id erat. Aliquam erat 
    volutpat. Praesent ultrices quam justo, nec condimentum elit 
    imperdiet at. Duis a fringilla quam. Suspendisse condimentum 
    gravida volutpat.
</p>