提问者:小点点

如何使用jQuery对指定字符中出现的所有子字符串进行着色?


我正在使用循环方法检测指定字符[]中出现的所有不同子字符串,我希望所有这些子字符串(从用户输入中检索)都具有红色。 但是只有最后一个这样的子字符串显示红色,而在它之前的所有子字符串都没有红色!

编辑:更改代码片段中输入部分的文本,以检查代码是否正常运行!

看看我到目前为止都做了些什么。

null

```
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.1.1.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
 span{
 color:red;
}
</style>
</head>
 <body style="background:rgba(20,10,30,1);">
 <input id="inp" style="height:20vh; width:80vw; background:royalblue; color:white; font-weight:bold;" value="I can [talk] but if you want a punch then I can [fight] too!" />
 <p style="color:white; font-weight:bold; text-shadow:.5vw .5vw .5vw black;"></p>
  <script>
  $(function(){
  $("#inp").on("input" , function(){
   var inp1 = $(this).val();
   $("p").html(inp1);
   var i = 0;
var j = 0;
var str = $("p").text();
var arry = [ ];
   for(i = 0; i < str.length; i++){
if(str[i] === "["){
arry.push(i);
 for(j = 0; j < str.length; j++){
  if(str[j] === "]" && i<j){
    arry.push(j);
    var newinp = "<span>"+str.slice(i , j+1)+"</span>";
$("p").html(str.slice(0 , i)+newinp+str.slice(parseInt(j)+parseInt(1) , str.length));
        }
            }
            }
        }
        });
        });             
    </script>
</body>
</html>

null


共1个答案

匿名用户

尝试使用regular表达式而不是嵌套循环

null

$(function(){
  $("#inp").on("input" , function(){
   var inp1 = $(this).val();
   $("p").html(inp1);
   var str = $("p").text();
   
    var result = str.replace(/(\[(?:[^\[\]]*)*\])/g, function (match) {
      return match.replace(/(\w+)/g, '<span>$1</span>');
      });
  
    $("p").html(result);
  
  });
});  
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.1.1.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
 span{
 color:red;
}
</style>
</head>
 <body style="background:rgba(20,10,30,1);">
 <input id="inp" style="height:20vh; width:80vw; background:royalblue; color:white; font-weight:bold;" value="I can [talk] but if you want a punch then I can [fight] too!" />
 <p style="color:white; font-weight:bold; text-shadow:.5vw .5vw .5vw black;"></p>
</body>
</html>