[英]How to convert data attribute value to integer for in javascript?
我一直在到處尋找這個,似乎找不到有效的解決方案。 我所擁有的是帶有箭頭和按鈕的滑塊,當單擊箭頭或按鈕時,該功能將獲取data-cs屬性,該屬性用於確定下一張幻燈片。
HTML
<div id="arrowleft" class="sliderbtns flip" data-sc="prev"></div>
<div id="arrowright" class="sliderbtns" data-sc="next"></div>
<div id="buttons" class="sliderbtns">
<div class="selectedbtn sliderbtns" id="button1" data-sc="1"></div>
<div class="button sliderbtns" data-sc="2"></div>
</div>
JavaScript
$( ".sliderbtns" ).click(function() {
var button_data = $(this).attr('data-sc');
myslider(button_data);
});
js中的功能
function myslider(position) {
if (position == "next" && (currentslide == slidecount)) {
position = 1;
} else if (position == "next") {
position = currentslide + 1;
} else if ((position == "prev") && (currentslide == 1)){
position = slidecount;
} else if ((position == "prev")) {
position = position - 1;
} else {
// position must then eqauls some integer from the data-sc attribute
position = parseInt(position);
alert (position); // alerts properly the first time
var out_slide = "Slide" + currentslide + "Out";
var next_slide = "Slide" + position;
alert(out_slide); //these work fine the first time
alert(next_slide);
window[next_slide]();
window[out_slide]();
// later on in the slide currentslide becomes position after this it returns value of Nan
setTimeout( function() {
currentslide = position;
alert("this is the current slide position" + currentslide);
}, 2000);
/* ommited code */
}
}
如果我僅單擊箭頭,則箭頭工作正常,但是當我單擊按鈕時,它會正確轉到下一張幻燈片,但是所有按鈕都不再起作用,並且將當前位置顯示為NaN,我試圖將位置變量設置為int一堆使用Number(position),ToInt和ParseInt的方法,但是在currentslide = position之后,它仍然以Nan形式返回它,並且滑塊不再能夠找到合適的幻燈片和功能,等等。。。可能做錯了,如果可以通過data屬性來確定它是否是一個實際的整數,或者我可以通過單擊箭頭或按鈕將這些數據作為in和int拋出,可以采用其他方法。 非常感謝您的幫助!
要獲取數據,請使用.data()
:
$(this).data('sc')
似乎沒有人閱讀問題。
NaN應該由於以下原因出現:
position = currentslide + 1;
從代碼中,我看不到currentslide
正在初始化。 如果undefined + 1
,則得到NaN
。
全局設置currentSlide = 0
使其正常工作。 除非您隱藏代碼。
ps。 標題與說明中提出的問題不符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.