寻找回文和连接字符串的问题

时间:2018-02-07 15:30:37

标签: javascript html html5

我是编程和使用HTML和JavaScript进行字符串回文和连接程序的新手。



function perform() {
  var a = document.getElementById("t1").value;
  var b = document.getElementById("t2").value;

  if (document.getElementById('p1').checked) {
    if (a === a.split("").reverse().join("")) {
      document.getElementById("d").innerHTML = a + " is a Palindrome";
    }
  } else if (document.getElementById('p2').checked) {
    document.getElementById("d").innerHTML = a + " " + b;
  }
}

document.getElementById("submit").addEventListener('click', perform);

Enter First String <input type="text" id="t1"><br>
Enter Second String <input type="text" id="t2"><br><br>

<input type="radio" name="r" id="p1"> Palindrome <br>
<input type="radio" name="r" id="p2"> Concatenate <br>
<input type="radio" name="r" id="p3"> Length <br>
<input type="radio" name="r" id="p4"> Compare <br>
<input type="radio" name="r" id="p5"> Substring position <br>
<input type="radio" name="r" id="p6"> IndexOf <br>
<input type="radio" name="r" id="p7"> Lowercase <br>
<input type="radio" name="r" id="p8"> Uppercase <br><br>
<button type="button" id="submit">Submit</button>
<div id="d">
&#13;
&#13;
&#13;

回文和连接代码都没有在我的代码中运行。

建议的任何更改都会有所帮助。

1 个答案:

答案 0 :(得分:0)

首先,你有一些不带&#34的字符串; &#34;标记在它们周围,这导致代码失败。

其次,通过一些小的调整,代码工作得很好。

看一下:(在代码的末尾,您找到了一个指向jsFiddle示例的工作链接)

<html>

  <head>
    <script>
      function perform() {
        var a = document.getElementById("t1").value;
        var b = document.getElementById("t2").value;

        if (document.getElementById('p1').checked) {
          var aReversed = a.split("").reverse().join("");
          if (a == aReversed) {
            document.getElementById("d").innerHTML = a + " is a Palindrome";
          } else {
          document.getElementById("d").innerHTML = a +  " is not a Palindrome";
          }

        } else if (document.getElementById('p2').checked) {
          document.getElementById("d").innerHTML = a + " " + b;
        }

      }

    </script>
  </head>

  <body>

    Enter First String
    <input type="text" id="t1">
    <br>
    <br> Enter Second String
    <input type="text" id="t2">
    <br>
    <br>

    <input type="radio" name="r" id="p1"> Palindrome
    <br>
    <input type="radio" name="r" id="p2"> Concatenate
    <br>
    <input type="radio" name="r" id="p3"> Length
    <br>
    <input type="radio" name="r" id="p4"> Compare
    <br>
    <input type="radio" name="r" id="p5"> Substring position
    <br>
    <input type="radio" name="r" id="p6"> IndexOf
    <br>
    <input type="radio" name="r" id="p7"> Lowercase
    <br>
    <input type="radio" name="r" id="p8"> Uppercase
    <br>
    <br>
    <input type="button" onclick="perform()" value="Submit">
    <div id="d">

  </body>

</html>

https://jsfiddle.net/xuag2z8p/3/

最诚挚的问候:)