我想更改 keyup 事件中空格后的最后两个字符,但我只想在第二个 textarea (#ta_2) 中更改。仅当我影响第一次输入 textarea (#ta_1) 时的修改值时,它才会更改。我该怎么做?

$(document).ready(function() { 
  $("#ta_1").keyup(function(event) { 
    var text = $(this).val().replace(/ (ak)+$/g, " AK"); 
    //$("#ta_1").val(text); 
    $("#ta_2").val(text); 
  }); 
});
<!DOCTYPE html> 
<html lang="en"> 
<head> 
  <title></title> 
  <meta charset="utf-8" /> 
 
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
</head> 
 
<body> 
  <textarea id="ta_1" rows="5" cols="28"></textarea> 
  <textarea id="ta_2" rows="5" cols="28"></textarea> 
</body> 
</html>

请您参考如下方法:

老式的 indexOf()lastIndexOf()slice() 怎么样:

$(document).ready(function() { 
    $("#ta_1").keyup(function(event) { 
        var text = $(this).val(); 
        var start = text.lastIndexOf(' ak') 
        // we take the last occurence of ' ak' in the string 
        // and replace if with ' AK' 
        if( text.indexOf(' ak') > -1) 
            text = text.slice(0,start) + ' AK' + text.slice(start+3) 
        // we set the second textarea value 
        $("#ta_2").val(text); 
    }); 
}); 

the fiddle

编辑

text = text.slice(0,start) + ' AK' + text.slice(start+3) 替换为 text = text.replace(/ak/g, ' AK')

$(document).ready(function() { 
    $("#ta_1").keyup(function(event) { 
        var text = $(this).val(); 
        if( text.indexOf(' ak') > -1) 
            text = text.replace(/ ak/g, ' AK') 
        // we set the second textarea value 
        $("#ta_2").val(text); 
    }); 
}); 

参见update fiddle


评论关闭
IT虾米网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!