为什么这个.innerHTML脚本不起作用?

时间:2017-08-30 12:06:15

标签: javascript

我试图在点击时更改文字链接。

这是我的代码



if (document.getElementById("morecat").innerHTML === '1')
		document.getElementById("morecat").innerHTML = '2';
        else {
        document.getElementById("morecat").innerHTML = '1';
    }

<a id="morecat" >1</a>
&#13;
&#13;
&#13;

然而,它不起作用,你们中任何人都能看到问题吗?

5 个答案:

答案 0 :(得分:1)

您需要将脚本包装在指定给onClick()的函数中。

<a id="morecat" onClick="changeText()" >1</a>
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch: UITouch = touches.first {
        let location = touch.location(in: self.view)
        let touchedView = self.view.hitTest(location, with: event)

        print(touchedView.restorationIdentifier)
    }
}

答案 1 :(得分:0)

您需要将其包装在changeText()方法调用中。

&#13;
&#13;
function changeText() {
  if (document.getElementById("morecat").innerHTML === '1')
    document.getElementById("morecat").innerHTML = '2';
  else {
    document.getElementById("morecat").innerHTML = '1';
  }
}
&#13;
<a id="morecat" onClick="changeText()">1</a>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

您必须在changeText函数中编写该代码,如此

&#13;
&#13;
function changeText(){
  if (document.getElementById("morecat").innerHTML === '1'){
      document.getElementById("morecat").innerHTML = '2';
   }
  else {
     document.getElementById("morecat").innerHTML = '1';
  }
}
&#13;
<a id="morecat" onClick="changeText()" >1</a>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

它的工作原理应该是:

  • <a id="morecat" >1</a>的innerHTML是字符串1
  • 根据您的条件:if (document.getElementById("morecat").innerHTML === '1')将内容设置为字符串2
  • 显示
  • 2

我已经添加了一个计时器来查看&#34;&#34;它改变了:

&#13;
&#13;
setTimeout(function(){ 
	console.log("morecat value is " + document.getElementById("morecat").innerHTML);

  if (document.getElementById("morecat").innerHTML === '1'){
    document.getElementById("morecat").innerHTML = '2';
  }
  else {
     document.getElementById("morecat").innerHTML = '1';
    }
 console.log("morecat value is " + document.getElementById("morecat").innerHTML);
    
 }, 3000);
&#13;
<a id="morecat">1</a>
&#13;
&#13;
&#13;

答案 4 :(得分:0)

您必须定义一个名为changeText的函数作为事件侦听器。此外,您不应该进行不必要的getElementById电话。对于更改,您可以在if then else块的位置使用逻辑短路。另一件需要提及的是检查textContent属性而不是innerHTML。如;

function changeText(){
  var mc = document.getElementById("morecat");
  mc.textContent === "1" && (mc.textContent = "2");
}
<a id="morecat" onClick="changeText()" >1</a>