JQuery:如何撤消对DOM的更改?

时间:2014-06-24 09:06:51

标签: jquery

我修改了选择更改的价格属性。

如何在其他条件下恢复正常价格?

jQuery( document ).ready(function( $ ) {
    $('#select_1').on('change', function() {
    var visit_time_val=$(this).val();

    if(visit_time_val==93 || visit_time_val==95)
    {
        var adult_price=26;
        var child_price=10;

        $('#select_15 option:nth-child(2)').attr("price",adult_price);
        $('#select_15 option:nth-child(3)').attr("price",adult_price*2);
        $('#select_15 option:nth-child(4)').attr("price",adult_price*3);
        $('#select_15 option:nth-child(5)').attr("price",adult_price*4);   

        $('#select_3 option:nth-child(2)').attr("price",child_price);   
        $('#select_3 option:nth-child(3)').attr("price",child_price*2);  
        $('#select_3 option:nth-child(4)').attr("price",child_price*3);  


    }
    else
    {
        //back to prices setted in db
    }
     });
});

2 个答案:

答案 0 :(得分:1)

试试这个:

    var previous;

    $("#select_1").one('focus', function () {
        // Store the current value on focus and on change
        previous = this.value;
    }).change(function() {
        var visit_time_val=$(this).val();

    if(visit_time_val==93 || visit_time_val==95)
    {
        var adult_price=26;
        var child_price=10;

        $('#select_15 option:nth-child(2)').attr("price",adult_price);
        $('#select_15 option:nth-child(3)').attr("price",adult_price*2);
        $('#select_15 option:nth-child(4)').attr("price",adult_price*3);
        $('#select_15 option:nth-child(5)').attr("price",adult_price*4);   

        $('#select_3 option:nth-child(2)').attr("price",child_price);   
        $('#select_3 option:nth-child(3)').attr("price",child_price*2);  
        $('#select_3 option:nth-child(4)').attr("price",child_price*3);  


    }
    else
    {
        //back to prices setted in db
        $(this).val(previous );
    }
    });

答案 1 :(得分:0)

您可以将值存储在Select标记的数据属性中,以便您可以使用该值。

<select id="select_1" data-selectedvalue="10">
<option>1</option>
<option>2</option>
<option>3</option>
<option selected>10</option>
</select>

jQuery( document ).ready(function( $ ) {
    $('#select_1').on('change', function() {
    var visit_time_val=$(this).val();

    if(visit_time_val==93 || visit_time_val==95)
    {
        var adult_price=26;
        var child_price=10;

        $('#select_15 option:nth-child(2)').attr("price",adult_price);
        $('#select_15 option:nth-child(3)').attr("price",adult_price*2);
        $('#select_15 option:nth-child(4)').attr("price",adult_price*3);
        $('#select_15 option:nth-child(5)').attr("price",adult_price*4);   

        $('#select_3 option:nth-child(2)').attr("price",child_price);   
        $('#select_3 option:nth-child(3)').attr("price",child_price*2);  
        $('#select_3 option:nth-child(4)').attr("price",child_price*3);  


    }
    else
    {
        $(this).val($(this).data("selectedvalue"));
    }
     });
});