如果p值==字符串不起作用

时间:2017-12-19 19:05:38

标签: javascript jquery

我开始用jQuery学习javascript。

我有以下代码:



$(document).ready(function(){
    $("#p1").click(function(){

        var input = document.getElementById("p3");

        if (input.value == "Hi")
        {
            message = "Bye";
        } else {
            message = "Hi";
        }

        $("#p3").text(message);
    });

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div1">

    <p id="p1">Click on me.</p>
    <p id="p2">Click on me again.</p>
    <p id="p3">Click on me one more time.</p>

</div>
    
&#13;
&#13;
&#13;

它在p1的第一次点击中起作用,但是当我再次点击它时,它不会改为&#34;再见&#34;

3 个答案:

答案 0 :(得分:3)

这是一个p aragraph,而不是input,因此.value无法满足您的需求。而是使用.textContent

$(document).ready(function() {
  $("#p1").click(function() {

    var input = document.getElementById("p3");

    if (input.textContent == "Hi") {
      message = "Bye";
    } else {
      message = "Hi";
    }

    $("#p3").text(message);
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div1">

  <p id="p1">Click on me.</p>
  <p id="p2">Click on me again.</p>
  <p id="p3">Click on me one more time.</p>

</div>

这是一个no-jQuery版本:

document.addEventListener("DOMContentLoaded", function() {
  document.querySelector("#p1").addEventListener("click", function() {
    var p3 = document.getElementById("p3");
    p3.textContent = p3.textContent == "Hi" ? "Bye" : "Hi";
  });
});
<div id="div1">
  <p id="p1">Click on me.</p>
  <p id="p2">Click on me again.</p>
  <p id="p3">Click on me one more time.</p>
</div>

答案 1 :(得分:0)

为了保持一致,我用jQuery查看p3并使用text()方法。

&#13;
&#13;
$(document).ready(function(){
    var $p3 = $('#p3');
    
    $("#p1").click(function(){
      var message = "Hi";
      
      if ($p3.text() === "Hi") message = "Bye";

      $p3.text(message);
    });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div1">

    <p id="p1">Click on me.</p>
    <p id="p2">Click on me again.</p>
    <p id="p3">Click on me one more time.</p>

</div>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

首先,if (input.value == "Hi")将始终返回false,因为输入值未定义,因此始终显示“Hi”