数字解析在控制台中工作但不在脚本中工作

时间:2016-11-03 18:52:44

标签: javascript jquery dom

这是我的简单函数,它在元素上被调用onclick="incrementValue(this)"

function incrementValue(plusElement) {
  var choicesLeft = jQuery("#choicesLeft");

  choicesLeft.innerHTML = Number(choicesLeft.innerHTML) - 1;
  console.log(choicesLeft.innerHTML);
};

console.log行在控制台中打印出 NaN

但是,当我在控制台中输入此行时:

choicesLeft.innerHTML = Number(choicesLeft.innerHTML) - 1;

发生预期的行为。

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

因为你在jQuery对象上调用它,所以

innerHTML在这里不起作用。

使用text()代替innerHTML

choicesLeft.text( Number(choicesLeft.text()) - 1 );

希望这有帮助。



function incrementValue() {
  var choicesLeft = jQuery("#choicesLeft");

  choicesLeft.text( Number(choicesLeft.text()) + 1 );
};

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onClick='incrementValue()'>Increment</button>
<br>
<span id='choicesLeft'>0</span>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您的代码包含几个问题:

function incrementValue(plusElement) {
  var choicesLeft = jQuery("#choicesLeft");

  choicesLeft.innerHTML = Number(choicesLeft.innerHTML) - 1;
  console.log(mealsLeft.innerHTML);
};

首先使用已经使用的参数 plusElement

其次你将javascript与jquery混合。

choicesLeft ,是一个jquery对象,您应该使用jquery api进行交互。

所以你应该有一些东西:

var choicesLeftNum = Number(choichesLeft.text());

var choicesLeftNum = +choichesLeft.text();

或     var choicesLeftNum = parseInt(choichesLeft.text(),10);

比你可以减少:

choichesLeft.text(choicesLeftNum - 1);

您应该使用 text()而不是 html(),因为您不需要html内容(如果有的话)。你对整篇文章没问题。