起初它说它不是一个功能,现在只是不做任何事情

时间:2018-08-08 22:48:05

标签: javascript jquery function

好的,我正在尝试制作一个俗气的口音发生器以与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>

1 个答案:

答案 0 :(得分:2)

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

如果您将该分配移至函数maccent()中(并将工作“标记”移回其所属的注释中),则页面将正常工作。

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