javascript - 单击 if 语句不起作用

标签 javascript jquery

有人可以向我解释一下为什么它有效吗:

  function updateWellnessPrice() {
        $('#toggle_151, #toggle_170').click(function () {
            amount = '1.50';
            $('#toggle_153 input').attr('data-amount', amount);
            $('#toggle_153 span').html(amount);
        });

    $('#toggle_148, #toggle_149, #toggle_150, #toggle_167, #toggle_168, #toggle_169').click(function () {
        amount = '0';
        $('#toggle_153 input').attr('data-amount', amount);
        $('#toggle_153 span').html(amount);
    });
};

但是我不喜欢那个代码,我想用人手不足的方式来编写它。为什么下面的代码不起作用?

  $('#toggle_151, #toggle_170').click(function () {
        var $this = $(this);
        if($this.data('clicked') == true) {
            amount = '1.50';
        } else {
            console.log('check');
            amount = '0';
        }
        $('#toggle_153 input').attr('data-amount', amount);
        $('#toggle_153 span').html(amount);
    });

甚至连控制台日志也没有显示出来,所以他不喜欢那个点击函数中的 else。

最佳答案

不确定您的 if 条件在这里是否有意义

试试这个

$('#toggle_148, #toggle_149, #toggle_150, #toggle_167, #toggle_168, #toggle_169, #toggle_151, #toggle_170').click(function () {
    var currentId = $(this).attr( "id" );
    if( currentId == "toggle_151" || currentId == "toggle_170" ) 
    {
        amount = '1.50';
    } 
    else 
    {
        console.log('check');
        amount = '0';
    }
    $('#toggle_153 input').attr('data-amount', amount);
    $('#toggle_153 span').html(amount);
});

现在假设您要为所有 id 编写一个单击处理程序。

关于javascript - 单击 if 语句不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37068974/

相关文章:

javascript - 查找属性所属的对象

jquery - 当我单击要删除的类时如何删除类

javascript - fotorama 如何使用 ajax

jquery - 如何在单击元素时传递 jquery 范围?

jquery - css + jQuery 下拉子菜单溢出

javascript - 禁用 Mozilla Firefox 任务栏上的绿色下载通知进度条

javascript - 迭代器和可迭代器之间的区别

java - Android 3.1 WebView 溢出滚动 - 不在滚动上呈现长列表

javascript - jQuery 与 css 属性切换

javascript - 更改浏览器选项卡时,JQuery 进度条暂停