2014-11-22 57 views
0

DEMO爲什麼變量會被識別爲JS中的一個數字?

我努力使網站的,用戶可以加上或減去一個按鈕來顯示或帶走更多的HTML元素的簡單的一部分。

但是我可以通過設置一個數字來有效地做到這一點。但是當我使用輸入框的值時它不起作用。這個輸入框可以被添加或減去,這取決於點擊的按鈕以及該部分工作正常。

HTML:

<p> 
    <img src="http://i.imgur.com/yOadS1c.png" id="minus2" width="20" height="20" class="minus"/> 
    <input id="qty2" type="text" value="1" class="qty"/> 
    <img id="add2" src="http://i.imgur.com/98cvZnj.png" width="20" height="20" class="add"/> 
</p> 

<div class="thisdiv"></div> 
<div class="thisdiv"></div> 
<div class="thisdiv"></div> 
<div class="thisdiv"></div> 
<div class="thisdiv"></div> 

CSS:

.thisdiv { 
    width:100px; 
    height:100px; 
    float:left; 
    clear:both; 
    border:1px solid black; 
    margin-bottom:10px; 
} 

JS:

$(function() { 
    // Automatically hide all the thumbnails 
    $('.thisdiv').hide(); 

    // When the add button is clicked 
    $('.add').on('click',function(){ 
    // Find the nearest value of p and set qty to equal the value in the input box 
    var $qty=$(this).closest('p').find('.qty'); 
    // Set variable currentVal to the new value of the qty 
    var currentVal = parseInt($qty.val()); 
    // If the current value is a number then add one. 
    if (!isNaN(currentVal)) { 
     $qty.val(currentVal + 1); 
    } 
    // Return debug message 
    console.log("ADDED ONE. VALUE NOW: " + (currentVal + 1)); 

    // This should set the number of divs to display to the 
    // value of currentVal, but it does not work? 

    $('.thisdiv:lt(currentVal)').show(); 
    }); 

    // When the minus button is clicked 
    $('.minus').on('click',function(){ 
    // Find the nearest value of p and set qty to equal the value in the input box 
    var $qty=$(this).closest('p').find('.qty'); 
    // Set variable currentVal to the new value of the qty 
    var currentVal = parseInt($qty.val()); 
    // If the current value is more than 0 and is a number then minus one 
    if (!isNaN(currentVal) && currentVal > 0) { 
     $qty.val(currentVal - 1);    
    } 
    // Return debug message 
    console.log("SUBTRACTED ONE. VALUE NOW: " + (currentVal - 1)); 

    // This should set the number of divs to display to the 
    // value of currentVal, but it does not work? 
    $('.thisdiv:lt(currentVal)').show(); 
    }); 
}); 

如果用替換currentVal實際的數字它的工作原理顯示數字 但這不是像我想要的那樣動態。爲什麼currentVal不工作? 這裏的例子工作$('.thisdiv:lt(2)').show();$('.thisdiv:lt(currentVal)').show();甚至沒有currentVal是一個有效的數字。

回答

1

$('.thisdiv:lt(currentVal)').show();完全不使用變量currentVal,它只是將文字文​​本'currentVal'作爲選擇器字符串的一部分。試試這個:

$('.thisdiv:lt(' + currentVal + ')').show(); 

這樣可以將較短的字符串'.thisdiv:lt('與變量currentVal的價值,並在末端短串')'

請注意,您似乎已經知道這一點,因爲你已經在使用以下行代碼的原理相同:

console.log("SUBTRACTED ONE. VALUE NOW: " + (currentVal - 1)); 
+0

好極了,解決了該問題。代表我犯了一個愚蠢的錯誤。 – LukeXF 2014-11-22 06:13:28

+0

現在的問題是添加演示作品。但不是減法。任何想法爲什麼? – LukeXF 2014-11-22 06:23:53

+0

在你的問題中的演示鏈接似乎適用於增加和減少(但也許你已經從你的評論四小時前更新它)。 – nnnnnn 2014-11-22 11:22:07

相關問題