Javascript jQuery不更改警报消息
我正在制作一个小费计算器,一切正常,但是如果选择了不同的评分,jQuery不会改变公式;e、 g,差,好,好 JSFIDLE演示:: 试试这个:Javascript jQuery不更改警报消息,javascript,jquery,if-statement,Javascript,Jquery,If Statement,我正在制作一个小费计算器,一切正常,但是如果选择了不同的评分,jQuery不会改变公式;e、 g,差,好,好 JSFIDLE演示:: 试试这个: jQuery(document).ready(function () { var theAmountVal=0; jQuery('#tip').onclick(function(){ if($('#poor').click && $('#amount').val().length){
jQuery(document).ready(function () {
var theAmountVal=0;
jQuery('#tip').onclick(function(){
if($('#poor').click && $('#amount').val().length){
theAmountVal = $('#amount').val();
alert(parseInt(theAmountVal)* .10);
} else if($('#good').click && $('#amount').val().length){
theAmountVal = $('#amount').val();
alert(parseInt(theAmountVal)* .15);
} else if($('#great').click && $('#amount').val().length){
theAmountVal = $('#amount').val();
alert(parseInt(theAmountVal)* .20);
} else {
alert("An error has occured.");
}
});
并删除此$'good'。从代码中单击,将其替换为其他内容。
.Click-是事件,不能在IF..ELSE结构中使用。事实并非如此。单击“工作…”
.click是一个触发单击或添加事件绑定的函数
您应该尝试适用于其他元素的条件x3:
if($('#poor').hasClass('active-state')&& $('#amount').val().length)
.hasClass将检查它是否具有类并返回true或false
这是.hasClass的文档:
此外,如果我可以给您一个建议,您可以在自定义属性中添加因子,如下所示:
<h1 id="poor" data-factor='.10' data-clicked="false">Poor</h1>
<h1 id="good" data-factor='.15' data-clicked="false">Good</h1>
<h1 id="great" data-factor='.20' data-clicked="false">Great</h1>
小提琴:这里有一个建议:
我得到了单击选项的id并将其存储在一个变量中,然后我使用了您的代码并重新检查了if语句上的id。我不认为$poor。单击意味着您认为它的意思。。。您可能希望有一个变量来存储是否单击了poor、good或great,并使用该变量而不是$poor。clickI建议您将选项设置为poor、good和great单选按钮,然后检查所选的值。感谢您的建议!谢谢,伙计,这很好用!我对身份证的作用有点困惑。我猜“id”代表h1,在if语句中,它检查h1的id是差的、好的还是好的?@mattnowstech,id是可以在html标记中使用的唯一标识符。使其独特非常有用。使用.prop,我读取您通过调用$'this'所单击的项目的属性id,并将其存储在一个变量中。@Sergio,为什么不选择=this.id@塞吉奥,我想说的是,不要用道具,用这个。我有同样的结果,但它比道具快:@Karl AndréGagnon,是的,当然,甚至更好。说得好+为了让生活更简单:@mattnowstech更新了我的答案,增加了一些优化。
<h1 id="poor" data-factor='.10' data-clicked="false">Poor</h1>
<h1 id="good" data-factor='.15' data-clicked="false">Good</h1>
<h1 id="great" data-factor='.20' data-clicked="false">Great</h1>
$('h1').on('click', function () {
$(this).addClass('active-state').siblings('h1').removeClass('active-state');
});
$('#tip').on('click', function(){
if($('.active-state').length && $('#amount').val().length){
var theAmountVal = $('#amount').val();
alert(theAmountVal * $('.active-state').data('factor'));
}
});
var choice;
$('h1').on('click', function () {
choice = this.id;
$(this).addClass('active-state').siblings('h1').removeClass('active-state');
});
$('#tip').on('click', function () {
if (choice == 'poor' && $('#amount').val().length) {
var theAmountVal = $('#amount').val();
alert(theAmountVal * .10);
} else if (choice == 'good' && $('#amount').val().length) {
var theAmountVal = $('#amount').val();
alert(theAmountVal * .15);
} else if (choice == 'great' && $('#amount').val().length) {
var theAmountVal = $('#amount').val();
alert(theAmountVal * .20);
} else {
alert("An error has occured.");
}
});