简体   繁体   English

每次运行jQuery函数时重置变量值

[英]Reset variable values each time a jQuery function runs

I want to run my function when the page first loads, and again when certain elements are clicked. 我想在页面首次加载时以及在单击某些元素时再次运行我的函数。 Each time this function is ran I need it to update the variables, but as it sits right now it is keeping the values that it found the first time the function ran. 每次运行此函数时,我都需要它来更新变量,但是由于它现在位于当前位置,因此它将保留它在第一次运行时发现的值。

I tried searching for this issue and found people saying to just set it to null, or undefined. 我尝试搜索此问题,发现有人说将其设置为null或未定义。 So I tried doing this by adding var price = null;, var x = null;, etc. at the end of the function. 因此,我尝试通过在函数末尾添加var price = null ;、 var x = null;等来执行此操作。 That didn't do anything. 那什么也没做。 So I tried adding an if statement at the top to see if price has a value greater than 0, and then changing every variable to null if it is. 因此,我尝试在顶部添加if语句以查看price是否具有大于0的值,然后将每个变量更改为null(如果是)。 This didn't change anything. 这并没有改变任何东西。 Now I'm not sure if I need to just re-write the entire thing, or maybe there is some other detail that I am missing? 现在,我不确定是否需要重新编写整个内容,或者是否缺少其他细节?

Thanks in advance for your help. 在此先感谢您的帮助。

    jQuery(document).ready(function(){

    var bessie = function(){

        //remove or reset value of variables for next time function runs
        if(price > 0){
        var qtyCode = null;
        var qty = null;
        var price = null;
        var total = null;
        var newContent = null;
        };

        //Pull html code for plus/minus qty selector
        var qtyCode = jQuery('.qtyswitcher-qty').html();

        //Get value of qty that is currently selected
        var qty = jQuery('#qtyswitcher-qty').val(); 

        //Pull the current price and change the string to a number
        var price = jQuery('.price').first().text().replace(/[^0-9\.]+/g,""); 

        //multiply price by qty to get the total for the users current selection
        var total = price * qty;

        //New html that will be inserted into the page
        var newContent = '<p class="multiply">' + '$' + price + '/ea</p>' + '<p class="multiply2">x</p>' + '<div id="qty">' + qtyCode + '</div>' + '<p class="multiply3">=</p> <p class="multiply">' + '$' + total.toFixed(2) + '</p>';

        //New html being inserted
        jQuery(".qtyswitcher-qty").replaceWith(newContent);
    };

    bessie();
    jQuery('.switcher-label').click(bessie);
    jQuery('#qtyswitcher-oneless').click(bessie);
    jQuery('#qtyswitcher-onemore').click(bessie);    

});

Moved some things around and added some new code based on Data's comments. 移动了一些内容,并根据Data的注释添加了一些新代码。 I'm not sure I did this correctly. 我不确定我是否正确地做到了。 I had also tried it with and without the parenthesis as was mentioned below. 我也尝试过使用或不使用括号,如下所述。 It's still staying as $9.00 even though you can see that the .price element is changing on the page when the items are clicked. 即使您看到单击项目时页面上的.price元素正在更改,它仍然保持为9.00美元。

Link to page with the html I am messing with 链接到我弄乱的html页面

<script type="text/javascript">

    var bessie = function(){

        //Pull html code for plus/minus qty selector
        var qtyCode = jQuery('.qtyswitcher-qty').html();

        //Get value of qty that is currently selected
        var qty = jQuery('#qtyswitcher-qty').val(); 

        //Pull the current price and change the string to a number
        var price = jQuery('.price').first().text().replace(/[^0-9\.]+/g,""); 

        //multiply price by qty to get the total for the users current selection
        var total = price * qty;

        //New html that will be inserted into the page
        var newContent = '<p class="multiply">' + '$' + price + '/ea</p>' + '<p class="multiply2">x</p>' + '<div id="qty">' + qtyCode + '</div>' + '<p class="multiply3">=</p> <p class="multiply">' + '$' + total.toFixed(2) + '</p>';

        //New html being inserted
        jQuery(".qtyswitcher-qty").replaceWith(newContent);
    }; 


    bessie();

    $('.switcher-label, #qtyswitcher-oneless, #qtyswitcher-onemore' ).on('dblclick click', function(e) { 
        bessie(e);
        e.stopImmediatePropagation();  
    });   


</script>

Found the problem now, but still working on a complete solution. 现在发现了问题,但仍在寻找完整的解决方案。 The .replaceWith(); .replaceWith(); was replacing the html in a way that made it not able to display updated info. 正在以无法显示更新信息的方式替换html。 The code below is working, but the problem now is that I need to find a way replace the html each time without breaking it. 下面的代码可以正常工作,但是现在的问题是,我需要找到每次都替换html而不破坏它的方法。 The way it sits now it is adding more html to the page when an element is clicked. 现在的坐姿是在单击元素时向页面添加更多html。 My code is still a bit messy. 我的代码仍然有点混乱。

<script type="text/javascript">
jQuery(document).ready(function() {

    var bessie = function(){

        //Pull html code for plus/minus qty selector
        var qtyCode = jQuery('.qtyswitcher-qty').html();

        //Get value of qty that is currently selected
        var qty = jQuery('#qtyswitcher-qty').val(); 

        //Pull the current price and change the string to a number
        var price = jQuery('.price').first().text().replace(/[^0-9\.]+/g,""); 

        //multiply price by qty to get the total for the users current selection
        var total = price * qty;

        //New html being inserted

        jQuery(".qtyswitcher-add-to-cart-box").append('<p class="multiply">' + '$' + price + '/ea</p>' + '<p class="multiply2">x</p>' + '<div id="qty">');

        jQuery(".qtyswitcher-qty").append('</div>' + '<p class="multiply3">=</p> <p class="multiply">' + '$' + total.toFixed(2) + '</p>');

    }; 

    bessie();
    jQuery('.switcher-label').click(bessie);
    jQuery('.input-box').click(bessie);
    jQuery('#qtyswitcher-oneless').click(bessie);
    jQuery('#qtyswitcher-onemore').click(bessie);

});
</script>

It's easier to separate html from javascript, so I recommend using handlebars. 将html与javascript分开更容易,因此我建议使用把手。 You pass an object and it returns html you can then use in jQuery. 您传递一个对象,它返回HTML,然后可以在jQuery中使用。 Notice the html string uses back-ticks to concatenate multi-line strings. 请注意,html字符串使用反引号连接多行字符串。

<script>

    var html = `<p class="multiply">${{price}}/ea</p>
                <p class="multiply2">x</p><div id="qty">{{qtyCode}}</div>
                <p class="multiply3">=</p><p class="multiply">'$'{{total}}</p>`;

    function bessie(){

        var obj = { 'qtyCode' : $('.qtyswitcher-qty').html(),
                    'qty'     : $('#qtyswitcher-qty').val(),
                    'price'   : $('.price').first().text().replace(/[^0-9\.]+/g,"") };

        obj.total = obj.price * obj.qty;

        var template = handlebars.compile(html),
            compiled = template(obj);

        $(".qtyswitcher-qty").replaceWith(compiled);

    };

    function addListeners(){
        $('.switcher-label').click(bessie());
        $('#qtyswitcher-oneless').click(bessie());
        $('#qtyswitcher-onemore').click(bessie()); 
    }

    $(document).ready( addListeners(); bessie(); );

</script>

Fixed it! 修复! Used insertBefore() and insertAfter() to add the html content where I wanted it. 使用insertBefore()和insertAfter()在需要的地方添加html内容。 Also added a div with the class remove me that will have .remove(); 还添加了一个带有该类的div删除我,将具有.remove(); used on it each time an element is clicked. 每次单击元素时在其上使用。

<script type="text/javascript">
jQuery(document).ready(function() {

    var bessie = function(){

        //Pull html code for plus/minus qty selector
        var qtyCode = jQuery('.qtyswitcher-qty').html();

        //Get value of qty that is currently selected
        var qty = jQuery('#qtyswitcher-qty').val(); 

        //Pull the current price and change the string to a number
        var price = jQuery('.price').first().text().replace(/[^0-9\.]+/g,""); 

        //multiply price by qty to get the total for the users current selection
        var total = price * qty;

        //New html being inserted

        jQuery( '<div class="removeMe"><p class="multiply">' + '$' + price + '/ea</p>' + '<p class="multiply2">x</p>' + '</div><div id="qty">' ).insertBefore( '.qtyswitcher-qty');
        jQuery( '</div>' + '<div class="removeMe"><p class="multiply3">=</p> <p class="multiply">' + '$' + total.toFixed(2) + '</p></div>' ).insertAfter( '.qtyswitcher-qty' );
    }; 

    bessie();
    jQuery('.switcher-label, .input-box, #qtyswitcher-oneless, #qtyswitcher-onemore' ).click(function() {
        jQuery( '.removeMe' ).remove();
        bessie();
});

});
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM