所以我的代码必须用jquery在javascript中更改"Eva have a cat“中的字母,但是我需要选择哪些字母将被更改为ex 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>
发布于 2019-04-25 02:51:10
从您的示例中可以看出,您并没有真正使用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>
https://stackoverflow.com/questions/55836483
复制相似问题