0

I can set action on click for html button. But I need to set action only on FIRST click. Is there any way to do this? The button is radio in form. Some javascript maybe?

What's important - the radio button still might be changed. But action has to be done only once.

This doesn't work

function myfunction(i){
oForm = document.forms["myform"];
if(oForm.elements["field"+i].checked)
    alert("action done earlier");
else
    action
}
4

5 回答 5

3

最干净的解决方案可能是使用removeEventListener来...删除事件侦听器:

var myButton = document.getElementById('someId');
var handler = function(){
   // doSomething
   myButton.removeEventListener('click',handler);
}
myButton.addEventListener('click', handler);

(为了使其更干净,您可以将其包装在 IIFE 中,如下例所示)

示范

于 2013-08-07T13:27:38.637 回答
1

查看 jQuery .one()事件处理程序。

$("#my-button").one('click', function() {
    /* Do something at most once */
});
于 2013-08-07T13:36:35.390 回答
0

为了解决这个问题,我使用了 jQuery.on 和 jQuery.off——在 jsfiddle 上查看我的代码!

$(document).ready(function() {
    var button = $('#my-button');

    function onClick() {
        alert('clicked');
        button.off('click', onClick);
    };

    button.on('click', onClick);
});

http://jsfiddle.net/VxRyn/

于 2013-08-07T13:31:16.743 回答
0

如果你更喜欢 jQuery,你可以使用 jQuery unbind

$("button").click(function(){
  /* some content */
  $(this).unbind('click');
});

html

<button> Some content </button>
于 2013-08-07T13:25:45.583 回答
0

单击按钮后,您可以使用属性禁用按钮,添加

disabled="disabled"

到按钮一次点击?

于 2013-08-07T13:30:39.337 回答