按下提交按钮后连接字符的javascript函数

时间:2014-11-23 17:52:37

标签: javascript

我正在尝试创建一个网页,其中包含一些按钮,每个按钮都有一个字母作为其值和一个提交按钮。按下提交按钮时,所有字母都应以字符串形式连接。 为此,我写了以下代码片段。但它不起作用。 (它给出了未定义的值。)

在返回myFunction.word后,我想将其设置为“”,以便下一组字符以新的字母开头。

<!DOCTYPE html>
<html>
<body>


<p id="demo"></p>

<script>
function myFunction(a) {
    this.word = '';
    if(a == ''){
         return myFunction.word;
    }
    else{
        myFunction.word += a;
        return '';
    }
}
</script>

<button type="button"
onclick="document.getElementById('demo').innerHTML = myFunction('a')">
A</button>

<button type="button"
onclick="document.getElementById('demo').innerHTML = myFunction('b')">
B</button>

<button type="button"
onclick="document.getElementById('demo').innerHTML = myFunction('c')">
C</button>

<button type="button"
onclick="document.getElementById('demo').innerHTML = myFunction('')">
Submit</button>
</body>
</html>
---------------

2 个答案:

答案 0 :(得分:1)

修改,更新

尝试

function myFunction(a) {
  if (!myFunction.word || a === "") {
    myFunction.temp = myFunction.word;
    myFunction.word = "";        
  };
  if (a.length >= 1) { myFunction.word += a };

  return a.length >= 1 ? "" : myFunction.temp;
};

&#13;
&#13;
function myFunction(a) {
  if (!myFunction.word || a === "") {
    myFunction.temp = myFunction.word;
    myFunction.word = "";
    
  };
  if (a.length >= 1) { myFunction.word += a };

  return a.length >= 1 ? "" : myFunction.temp;
};
&#13;
<p id="demo"></p>
<button type="button" onclick="document.getElementById('demo').innerHTML = myFunction('a')">
  A</button>

<button type="button" onclick="document.getElementById('demo').innerHTML = myFunction('b')">
  B</button>

<button type="button" onclick="document.getElementById('demo').innerHTML = myFunction('c')">
  C</button>

<button type="button" onclick="document.getElementById('demo').innerHTML = myFunction('')">
  Submit</button>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

对于一个简单的解决方案,我建议:

<p id="demo"></p>

<button type="button" class="letter">A</button>
<button type="button" class="letter">B</button>
<button type="button" class="letter">C</button>

<button type="button" 
      onclick="document.getElementById('demo').innerHTML = word; word = '';">
    Submit
</button>

<script>
    var word = "";
    var letters = document.getElementsByClassName('letter');
    for (var i=0; i < letters.length; i++) {
        letters[i].onclick = function (evt) {
            word += evt.target.innerHTML;
        }
    }
</script>