使用jquery进行下拉选择自动更新时需要帮助
我试图创建一种pc生成器,但是当使用下拉列表时,它不会更新价格使用jquery进行下拉选择自动更新时需要帮助,jquery,Jquery,我试图创建一种pc生成器,但是当使用下拉列表时,它不会更新价格 $(document).ready(function() { var total = 0; //Base price function calcTotal() { $("select").each(function() { //This happens for each checked input field var cost = $(this).val(); //I beleive the
$(document).ready(function()
{
var total = 0; //Base price
function calcTotal()
{
$("select").each(function()
{
//This happens for each checked input field
var cost = $(this).val(); //I beleive the problems are here and...
total += parseInt(cost); //total = total + cost
});
}
//This happens when the page loads
calcTotal();
$("form").before('<p class="total">Base Price of Your Custom PC: <strong>£' + total + '</strong></p>');
$(":submit").before('<p class="total">Base Price of Your Custom PC: <strong>£' + total + '</strong></p>');
$("input:checkbox, input:radio").click(function() //... and problem here?
{
total = 0; //Base price
calcTotal();
$("p.total").html("Total Cost of Your Custom PC: <strong>£" + total + "</strong>");
});
});
我的html在这里;
我使用cost=作为计算值,但当我加载html页面时,我得到的价格值为£NaN?我不能使用value属性,因为它用于另一个函数
有人能帮忙吗
请参见如果需要成本属性的值,则应使用$this.attr'cost'而不是$this.val-请参见jQuery的 也就是说,cost显然不是一个有效的html属性。你应该避免使用它。如果需要使用自定义属性,则应使用数据成本-请参阅
在将来,可能值得通过JS使用类似工具的工具进行调试,或者自由使用语句来缩小问题的范围。好的,单独回答,因为这里有很多问题: 首先,您尝试使用以下方法从所有选择中获取所选选项:
$('select').each(function() {/*...*/});
不行。你应该使用
在这里面,您还需要处理所选选项没有默认值的情况。我同意:
var id = $(this).attr('id');
if(typeof id !== 'undefined')
{
total += parseInt(id, 10); // Note: always supply a base when using parseInt
}
虽然可能有更整洁的方法。还要注意,您使用了parseInt'id',这是错误的。您想要解析id变量的值,而不是字符串“id”
最后,行:
$('').change(function() //Error must be here?
显然需要:
$('select').change(function()
总的来说,我可能也会改变一下结构,但这是另一天的故事。在这里使用JSFIDLE:Hi,我已经更改了id的成本,并在html和js文件中对此进行了修改,但是它不会在html上自动更新,我猜这是个问题$input:checkbox,input:radio.clickfunction改为input:checkbox,input:radio。这应该是选择、选择器还是选择等?谢谢你的帮助稍有更新。你会看到自动更新的价格比我想象的要高,但只是显示了我已经注释了我认为错误的地方。Ta非常有用,最有用的是,我猜可能有几个明显的错误:谢谢你的parseInt注释。
$('').change(function() //Error must be here?
$('select').change(function()