条件无法正常运作

时间:2015-06-28 12:15:05

标签: javascript

如果条件为真但不起作用。 x.innerHTML内部已有clicked me个内容,但条件没有响应。 当我运行代码并单击div标签时,它会显示job is done,而它应该是click me \n click me again

var x = document.getElementById("something") ;
x.addEventListener("click", istFunction) ;

function istFunction() {
  if ( x.innerHTML == "click me" ) {
    x.innerHTML += "<br> click me again" ;
  } else if (x.innerHTML == "click me <br> click me again") {
    x.innerHTML = "thank you" ;
  } else if (x.innerHTML == "thank you" ) {
    x.innerHTML = "good bye" ; 
  } else if (x.innerHTML == "good bye") { 
    x.style.display = "none" ; 
  } else if (x.innerHTML == "") {
    x.innerHTML == "click me" ;
  } else { x.innerHTML = "job is done" ;
         }
}
<div class="dclass" id="something">
click me
</div>

4 个答案:

答案 0 :(得分:1)

删除func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { if (textField == firstText){ var text = firstText.text as NSString if (text.length == 4){ secondText.becomeFirstResponder() } } if (textField == secondText){ var text = secondText.text as NSString if (text.length == 4){ successAction() } } return true; } 标记和空格:

<span>

答案 1 :(得分:0)

这是因为您第一次点击XXX x.innerHTML会返回<span>click me</span>。您可以删除span元素或使用x.innerText

答案 2 :(得分:0)

正如其他人提到的,你有几个问题,一个是innerhtml将包含span。如果您只删除跨度,它将包含一个预先添加的换行符,除非您将它全部放在一行上。其次,你试着匹配&#34;再次点击我之前用空格,但你没有在设置时添加一个空格。这是一个代码,我认为它展示了你想要实现的目标:http://codepen.io/socketwiz/pen/wapqyQ

var x = document.getElementById("something");
x.addEventListener("click", istFunction);

function istFunction(e) {
  console.log(x.innerHTML);
  if (x.innerHTML == "click me") {
    x.innerHTML += " <br> click me again";
  } else if (x.innerHTML == "click me <br> click me again") {
    x.innerHTML = "thank you";
  } else if (x.innerHTML == "thank you") {
    x.innerHTML = "good bye";
  } else if (x.innerHTML == "good bye") {
    x.style.display = "none";
  } else if (x.innerHTML == "") {
    x.innerHTML == "click me";
  } else {
    x.innerHTML = "job is done";
  }
}

答案 3 :(得分:-1)

您正在使用innerHTML,其中包含<span>的html。试试innerText

<div class="dclass" id="something">
<span>click me</span>
</div>
<script>
var x = document.getElementById("something") ;
x.addEventListener("click", istFunction) ;

function istFunction() {
    console.log("innerHTML:",x.innerHTML)
    console.log("innerText:",x.innerText)
}
</script>

输出:

innerHTML: <span>click me</span>
innerText: click me