在调用JS函数之前单击按钮进行验证

时间:2014-01-28 08:46:57

标签: javascript jquery

好的,我知道如何点击一个按钮时要求验证但我怎么能这样做,以便从点击它的同一个按钮首先要求验证,然后做我想要的JS功能?

例如

function clicked(e)
{
    if(!confirm('Are you sure you want to do this?'))e.preventDefault();
}

<button type="button" onclick="clicked(event)">Close Round 1</button>

我想做的是在确认后调用以下功能

function closer1() {...}

显然没有一个按钮,我可以以某种方式将按钮的id传递给被点击的功能,并以某种方式从那里调用该功能吗?

6 个答案:

答案 0 :(得分:1)

有什么问题
if(!confirm('Are you sure you want to do this?'))
{
   e.preventDefault();
   return false;
}
if(e=='button1') {
    closer1();
}

答案 1 :(得分:1)

var result = confirm("Are you sure you want to do this?");
if (result == false) {
  e.preventDefault(); // user pressed cancel
} else {
  closer1(); // user pressed ok
}

如果您的可点击按钮共享一个功能,您可以实现类似这样的功能,其结果会根据点击按钮的ID而变化

var result = confirm("Are you sure you want to do this?");
if (result == false) {
  e.preventDefault(); // user pressed cancel
} else if ($(this).attr('id') == 'button1') {
  closer1(); // user pressed ok, and request came from button 1
} else if ($(this).attr('id') == 'button2') {
  closer2(); // user pressed ok, and request came from button 2
}

答案 2 :(得分:1)

function clicked(event, element)
{
   if(!confirm('Are you sure you want to do this?'))
   {
      e.preventDefault();
      return false;
   }

   // you can use 'element' as your element that has been clicked
}

<button type="button" onclick="clicked(event, this)">Close Round 1</button>

答案 3 :(得分:1)

为什么不这样做?

<button type="button" onclick="closer1()">Close Round 1</button>

如果那不是您想要的,那么您可以这样做:

<button type="button" onclick="clicked('button1')">Close Round 1</button>

<强>的Javascript

function clicked(str){
   if(str=='button1')
      closer1();
   if(str=='button2')
      closer2();
   //and so on
}

答案 4 :(得分:1)


这就是我要做的事情:


HTML:

<button type="button" onclick="sample_one(event)">Close Round 1</button>

JS:

function sample_one(e)
{
    e.preventDefault(); // Stops default action

    // Ask for confirmation
    if ( confirm('Are you sure you want to do this?') )
    {
        sample_two(); // Call the second defined function
    }
}

function sample_two()
{
    alert('sample_two function called.'); // Alert message to show defined function call
}

以下是jsfiddle

示例

答案 5 :(得分:0)

function clicked(e){

   e.preventDefault();  

    var r = confirm("Are you sure you want to delete?");
    if (r == true) {

    } else { 
    return false;

    }

    }