好的,我正在尝试制作一个俗气的口音发生器以与RegEx一起练习。但是我有一个奇怪的问题,似乎与RegEx无关。提交按钮不执行任何操作。最初,功能“ maccent”仅被称为“ accent”,那时控制台说“ accent”不是功能。没什么好继续的,我认为这是因为“ accent”一词被使用了很多次,所以我将函数名称更改为“ maccent”。但是,现在什么也没有发生。这是怎么回事?这是我的代码:

<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="UTF-8">
<title>Accent Generator</title>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>


</head>
<body>
  <p>Choose an accent</p>
  <input type = "text">

  <form action="">
  <input type="radio" name="accent" value="German"> German<br>
  <input type="radio" name="accent" value="English"> English<br>
  <input type="radio" name="accent" value="Indian"> Indian
</form>

  <button type="submit" onclick = "maccent()">Submit</button>
  <div id = "accented"></div>


<script>

    var accent = $('input[name="accent"]:checked').val();



  function maccent()
  {
    if (accent == "German")
    {
      germAcc();
    }
  }

    function germAcc()
    {
var sample = $("input").val()


var desire = sample.replace(/[w]/gi, "v")
//not if it's at the end of a word

var desire2 = desire.replace(/th/, "z")
//replace h too, but not with another z.
//wait, what?  It replaces t even if its not followed by h

var desire3 = desire2.replace(/er/, "a")
//this is going to be a hard one
//er is replaced with a but only if its followed by a space or a punctuation
mark.
console.log(desire3);

}

function indAcc()
{
var sample = $("input").val()


var desire = sample.replace(/[r]/gi, "d")
//not if it's at the end of a word


//this words, but not on each indivual word

console.log(desire);

}

function itAcc()
{

}

function britAcc()
{
  var sample = $("input").val();


var desire = sample.replace(/[a]/gi, "au")

var desire2 = desire.replace(/er/, "a")
//this is going to be a hard one

console.log(desire2);


//not if it's at the end of a word
}




  </script>

  </body>
</html>

最佳答案

问题是“变量” accent的分配。您正在全局范围(顶层)上执行此操作,因此在首次加载页面时会对其进行分配。

如果将该分配移到函数maccent()中(并将工作“标记”移回到它所属的注释中),则页面将起作用。

顺便说一句,旧的问题是您有一个函数和一个变量试图共享名称accent。变量是“获胜”。

09-13 10:15