所以我的代码必须用javascript更改javascript中“ Eva的猫”中的字母,但我需要选择将所有字母更改为a-> t,但我的代码中有错误,请您帮忙我吗?
我认为mb我到jq的链接是错误的,因此我插入了到Google jq的链接,但它也不起作用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<form action="">
<input type="text"id="p1">
<input type="text"id="p2">
<input type="button"value="Click me"id="g">
</form>
<div></div>
<script>var p1;
var p2;
var zdj;
var div=document.querySelector('div');
$('#g').on('click',function(e){e.preventDefault();
var p1=document.querySelector('#p1');
var p2=document.querySelector('#p2');
var zdj="Eva has a cat";
for(let i=0;i<zdj.length;i++){
if(zdj.charAt(i)===p1.values()){zdj.charAt(i)=p2.values()}
}
div.innerText=zdj;
})
</script>
</body>
</html>
答案 0 :(得分:1)
从您的示例看来,您并不是真正在使用jQuery。 另外,将值赋给charAt()的结果也行不通。
最简单的方法是使用jQuery $
,并使用方法String.prototype.replace
,例如:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<form action="">
<input type="text"id="p1">
<input type="text"id="p2">
<input type="button"value="Click me"id="g">
</form>
<div></div>
<script>
var p1;
var p2;
var zdj;
// here you need to select the values using JQuery, not document.querySelector
var div=$('div');
$('#g').on('click', function(e){
e.preventDefault();
var p1=$('#p1');
var p2=$('#p2');
var zdj="Eva has a cat";
// Now you can create a regular expression from the value of p1.
// That value is retrieved using val(), not values()
var expression = new RegExp(p1.val(), "g");
// then you simply call string.replace passing that value
zdj = zdj.replace(expression, p2.val());
div.text(zdj);
});
</script>
</body>
</html>