javascript - 起初它说它不是一个函数,现在它只是什么也没做

标签 javascript jquery function

好吧,我正在尝试制作一个俗气的口音生成器来练习 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>

最佳答案

问题在于“变量”重音的分配。您是在全局范围(顶层)执行此操作,因此它会在页面首次加载时分配。

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

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

关于javascript - 起初它说它不是一个函数,现在它只是什么也没做,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51756677/

相关文章:

javascript - jquery/javascript 错误 - 太多递归 - 使用自调用函数

javascript - 根据唯一键/名称过滤状态数据数组并推送到新数组

javascript - 无法从另一个页面获取值

javascript - Chrome 中的事件绑定(bind) Ctrl-Shift-N

c++ - 引用 set for c++ 中的最大/最小 int

c++ - 在 C++ 中的函数名前使用 '&' 运算符

javascript - 将一个 div 移动到另一个 div

javascript - 使用 Service Worker 启用 COOP/COEP header : security concerns?

javascript - 等高JS

jquery - Bootstrap 样式不适用于打印