javascript / jQuery에서 문자열을 숫자로 변환
다음을 숫자로 변환하려고했습니다.
<button class="btn btn-large btn-info" data-votevalue="1">
<strong>1</strong>
</button>
var votevalue = parseInt($(this).data('votevalue'));
나도 시도 Number()
했지만 NaN
결과를 확인할 때 여전히 나타납니다. 내가 도대체 뭘 잘못하고있는 겁니까?
다음은 완전한 코드입니다.
<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
this
코드에서 .btn
요소를 참조하지 않는 것 같습니다 . 선택기를 사용하여 명시 적으로 참조하십시오.
var votevalue = parseInt($(".btn").data('votevalue'), 10);
또한 기수를 잊지 마십시오.
당신은 사용할 수 있습니다 에서는 parseInt (문자열, 기수)을 아래의 코드처럼 정수로 변환 문자열 값
var votevalue = parseInt($('button').data('votevalue'));
이것은 오래된 게시물이지만 간단한 함수가 코드를 더 읽기 쉽게 만들고 jQuery 체인 코드 스타일을 유지할 수 있다고 생각했습니다.
String.prototype.toNum = function(){
return parseInt(this, 10);
}
jQuery와 함께 사용할 수 있습니다.
var padding_top = $('#some_div').css('padding-top'); //string: "10px"
var padding_top = $('#some_div').css('padding-top').toNum(); //number: 10`
또는 모든 String
개체 :
"123".toNum(); //123 (number)`
You should just use "+" before $(this)
. That's going to convert the string to number, so:
var votevalue = +$(this).data('votevalue');
Oh and I recommend to use closest()
method just in case :)
var votevalue = +$(this).closest('.btn-group').data('votevalue');
It sounds like this
is referring to something else than you think. In what context are you using it?
The this
keyword is usually only used within a callback function of an event-handler, when you loop over a set of elements, or similar. In that context it refers to a particular DOM-element, and can be used the way you do.
If you only want to access that particular button (outside any callback or loop) and don't have any other elements that use the btn-info
class, you could do something like:
parseInt($(".btn-info").data('votevalue'), 10);
You could also assign the element an ID, and use that to select on, which is probably a safer way, if you want to be sure that only one element match your selector.
You can adding a +
before the string without using parseInt and parseFloat and radix, Simply
sample:
var votevalue = +$('button').data('votevalue');
alert(typeof(votevalue));
For your case, just use:
var votevalue = +$(this).data('votevalue');
There are some ways to convert string to number in javascript.
The best way:
var str = "1";
var num = +str; //simple enough and work with both int and float
You also can:
var str = "1";
var num = Number(str); //without new. work with both int and float
or
var str = "1";
var num = parseInt(str,10); //for integer number
var num = parseFloat(str); //for float number
DON'T:
var str = "1";
var num = new Number(str); //num will be an object. typeof num == 'object'
Use parseInt only for special case, for example
var str = "ff";
var num = parseInt(str,16); //255
var str = "0xff";
var num = parseInt(str); //255
var string = 123 (is string),
parseInt(parameter is string);
var string = '123';
var int= parseInt(string );
console.log(int); //Output will be 123.
var votevalue = $.map($(this).data('votevalue'), Number);
참고URL : https://stackoverflow.com/questions/12839567/converting-string-to-number-in-javascript-jquery
'Programing' 카테고리의 다른 글
ActiveRecord에서 반환 된 배열을 날짜 (또는 다른 열)별로 정렬 (0) | 2020.11.26 |
---|---|
존재가 true로 설정되지 않은 경우에도 Rails 유효성 검사에 숫자가 필요함 (0) | 2020.11.26 |
NSMutableAttributedString에서 링크 색상 변경 (0) | 2020.11.26 |
pip3로 패키지를 설치할 때 "Python의 SSL 모듈을 사용할 수 없습니다" (0) | 2020.11.26 |
명령 줄을 통해 Android 장치에서 수동으로 React Native 앱 다시로드 (0) | 2020.11.26 |