本文介绍了在javascript / jQuery中将字符串转换为数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
一直在尝试将以下内容转换为数字:
Been trying to convert the following to number:
<button class="btn btn-large btn-info" data-votevalue="1">
<strong>1</strong>
</button>
var votevalue = parseInt($(this).data('votevalue'));
我也试过 Number()
但是在检查结果时我仍然会得到 NaN
。我做错了什么?
I've also tried Number()
but I'm still getting NaN
when checking the result. What am I doing wrong?
这是完整的代码:
<div class="span7" id="button-group">
<div class="btn-group">
<button class="btn btn-large btn-info" data-votevalue="1"><strong>1</strong></button>
<button class="btn btn-large btn-info" data-votevalue="2"><strong>2</strong></button>
<button class="btn btn-large btn-info" data-votevalue="3"><strong>3</strong></button>
<button class="btn btn-large btn-info" data-votevalue="4"><strong>4</strong></button>
<button class="btn btn-large btn-info" data-votevalue="5"><strong>5</strong></button>
<button class="btn btn-large btn-info" data-votevalue="6"><strong>6</strong></button>
<button class="btn btn-large btn-info" data-votevalue="7"><strong>7</strong></button>
<button class="btn btn-large btn-info" data-votevalue="8"><strong>8</strong></button>
<button class="btn btn-large btn-info" data-votevalue="9"><strong>9</strong></button>
<button class="btn btn-large btn-info" data-votevalue="10"><strong>10</strong></button>
</div>
</div>
$('#button-group button').each(function() {
$(this).click(function() {
$(this).addClass('active');
var votevalue = parseInt($(this).data('votevalue'));
var filename = $('.mainimage').data('filename');
var votes = parseInt($('.mainimage').data('numvotes'));
var totalscore = parseInt($('.mainimage').data('totalscore'));
$.ajax({
type: 'POST',
url: 'index.php/?category=vote',
data: {
"votevalue": votevalue,
"filename": filename
},
success: function() {
votes++;
alert(votes);
var average = ((totalscore + votevalue) / votes);
$('#vote-incremenet').html(votes);
$('#display-average').html(average);
$('#display-average').show();
$('#button-group button').each(function(){
$(this).unbind('click');
});
}
}); // end ajax
}); // end click
}); // end each
推荐答案
听起来像您的代码中的此
不是指您的 .btn
元素。尝试使用选择器显式引用它:
It sounds like this
in your code is not referring to your .btn
element. Try referencing it explicitly with a selector:
var votevalue = parseInt($(".btn").data('votevalue'), 10);
另外,不要忘记基数。
这篇关于在javascript / jQuery中将字符串转换为数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!