简体   繁体   中英

jQuery onclick method doesn't work twice

I have 2 onclick methods. The first one works fine but the second one doesn't works if i click first one, I need to refresh the page to run. Even if I do that, it only works once.

    $(document).ready(function(){
    $(".cart_add").on('click','.add_cart',function(){
        var product_id = $(this).data("productid");
        var size = $('ul#size').find('li.active a').data('value');
        var qty = $('.qty-input').val();
        var price = $('.special-price').data('price');
        var name = $('h1.product-name').text();
        var url = $(this).data("url");
        $.post(url,{product_id:product_id,product_size:size,product_name:name,product_price:price,product_qty:qty},function(response){
            $(".variant-1").html(response);
        });
    });

    $(".secondary").on('click','.delete',function(){
        var product_id = $(this).data("id");
        var url = $(this).data("url");
        $.post(url,{product_id:product_id},function(response){
            $(".variant-1").html(response);
        });
    });
})

 $("#CheckClick").click(function(){ alert("The paragraph was clicked."); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button class="btn btn-success" id="CheckClick">button</button>

Take ID Instead of Class check in side your code or take your script inside function and call it on button click

 function myFunction(){ alert("it's work well") }
 <input id="clickMe" type="button" value="clickme" onclick="myFunction();" />

you can try using onclick event from html button like`

 function myFunction() { alert('"hello"'); }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button onclick="myFunction()">Click me</button>

e`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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