簡體   English   中英

如何在單擊jquery按鈕之前單擊JS函數(單擊選擇器)

[英]How to call a JS function before a jquery button click(click through selector)

我想在單擊按鈕時調用JS函數,然后繼續執行以下jquery腳本

形式:

<form id="my_form">
  <button type="button" id="Bshift" onclick="validation()">Clear</button>
</form>

純JS功能:

function validation(){
    // this has to be executed  first
    // do something here..
}

jQuery:

$(document).ready(function(){
    $('#Bshift').submit(function(){
    // this has to be executed  second
    // do something here.
    }
});

我想知道在我的jquery提交之前如何執行我的函數。

HTML:

  <form id="my_form">
    <button type="button" id="Bshift">Clear</button>
  </form>

JS:

$(document).ready(function(){
   $('#Bshift').on('click', function(){ // I think this should be click event because you're not submitting your page you're just clearing it based on "CLEAR"
     validation();
   }

   function validation(){
    do something here..
   }
 }

注意:您的函數必須在事件觸發器之外。

在提交調用中調用您的驗證功能。

$(document).ready(function(){

        $('#Bshift').submit(function(){
        validation()
        do something here.
        }
    }

HTML代碼

<button type="button" id="Bshift" >Clear</button>

驗證后,您還有一個選擇可以通過ajax提交表單。

$('my_form').on('submit', function(e) {
    e.preventDefault();
    if (validation()){
        $.ajax({...});
    }
});

修改后的代碼,請測試我的代碼。

<script>
function validation(){
    alert('How are you?');
}

$(document).ready(function(){
     $('#Bshift').click(function(){
         validation(); 
         alert('Fine and you?');           
     });
 });
</script>

<form id="my_form">
<button type="button" id="Bshift">Clear</button>
</form>

演示版

在表單提交事件上調用驗證功能

$(document).ready(function(){
    validation(); // function call

    $('#my_form').submit(function(){  //form submit event
    // do something here.
    }

});


function validation(){
 // do something here..
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM