简体   繁体   English

我的JavaScript有什么问题?

[英]What is wrong with my Javascript?

This is my jsfiddle(http://jsfiddle.net/mZGsp/). 这是我的jsfiddle(http://jsfiddle.net/mZGsp/)。 I was trying to answer a question here but my code won't work. 我试图在这里回答一个问题,但是我的代码无法正常工作。 Here is the code: 这是代码:

JS JS

var stateOfClick = null;

function initiateLine(){
    document.getElementById('test').innerHtml = "Started";
}

function endLine(){
    document.getElementById('test').innerHtml = "Line Ended";
}

function createLines(){
  if(!stateOfClick) {
    initiateLine();
    stateOfClick = 1;
  } else {
    endLine();
  }
}

HTML 的HTML

<body>
    <input type="text" id="test" onclick="createlines()">
</body>

A couple of things, 有几件事,

  • change createlines() to createLines (camel-case). 改变createlines()createLines (骆驼情况)。
  • change <element>.innerHtml to <element>.value <element>.innerHtml更改为<element>.value
  • Inside JSFiddle, don't wrap your code inside a function, as then createLines won't be global which it needs to be for the onclick to work. 里面的jsfiddle,不换行代码的函数里面,正如当时createLines不会是全球性的,它需要成为的onclick工作。

Here's a working example . 这是一个有效的例子

Not even this simple example will work on jsFiddle. 即使这个简单的示例也无法在jsFiddle上运行。 You need to attach the event listener with JavaScript: 您需要使用JavaScript附加事件监听器:

document.getElementById("someElement").onclick = function() {
  //Do stuff  
}

For input element you must use the value attribute not the innerHTML field. 对于输入元素,必须使用value属性,而不是innerHTML字段。

function initiateLine(){
    document.getElementById('test').value = "Started";
}

also you've misspelled the innerHTML function (though not the primary problem). 您也拼错了innerHTML函数(尽管不是主要问题)。 innerHTML is used for html elements that can contain other elements such as a div containg ap element. innerHTML用于可包含其他元素(例如div containsg ap元素)的html元素。 Input and option elements all have a value attribute that can be used to extract or set their values. 输入元素和选项元素均具有值属性,可用于提取或设置其值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM