How to auto click button in knockout js

2019-09-19 07:16发布

问题:

I have the below button on my page. I want below button to be auto clicked when this page gets loaded. I've tried following various suggestions on the net but I'm unable to find a solution. Any help is appreciated.

 <a data-bind="click: $root.addtocart" class="w-button btn-large" 
    style="text-decoration: none!important;" id="redeemButton">
                        Redeem Now                                                                               
 </a>

回答1:

Do it directly in the creation of your viewmodel:

function MyViewModel(){
    this.addtocart = function(){
      //Some code
    }
    this.addtocart(); // <-- here
}


回答2:

you can add a ready function in your javascript like this..

<script>
    $("document").ready(function () {
        window.getElementById("redeemButton").click();
    });
</script>