Javascript click events firing multiple times?

China☆狼群 提交于 2021-02-11 01:46:02

问题


Why is my function running multiple times?

var s,
getData = {

    settings: {
        gender: $("input[name='gender']"),
        age: $("input[name='age']")
    },

    init: function() {
        s = this.settings;
        this.getInput();
    },

    getInput: function() {
        for (i in s) {
            s[i].on("click", function() {
                s[i].off();
                console.log(this.getAttribute('value'))
            });
        }
    },
};

What I find odd is that when I don't click the same input twice it only runs once. For instance if I click 'male' and then 'female' it would show in the console

(1) male
(2) female

which logically makes sense to me, if I clicked 'male' 5 times then I get

(14) male

and it just gets larger and larger.

EDIT: JSFiddle If you open console you can see what happens


回答1:


What's happening is that getInput is being called for each click event, meaning that the loop is running each time, registering the event again. So each time you click the radio button the loop will attach an event to the DOM element again. You should only register the event once: https://jsfiddle.net/2jbLdo9n/

Remove the onclick event on the input:

<div class="right-item">
  <input id="male" type="radio" name="gender" value="male">
  <label class="left-m" for="male"><span></span> Male </label>
</div>
<div class="right-item">
  <input id="female" type="radio" name="gender" value="female">
  <label for="female"><span></span> Female </label>
</div>

Then in your JavaScript, just call getData.init();

getData.init();



回答2:


bind a single click event, if you are calling this multiple time then first remove the click event and the append it once again or use one()

try the following:

var s,
getData = {

    settings: {
        gender: "input[name='gender']",
        age: "input[name='age']"
    },

    init: function() {
        s = this.settings;
        this.getInput();
    },

    getInput: function() {

            $(s.gender+','+s.age).on("click", function() {
                console.log($(this).val());
            });
    },
};

remove the click event and initiate the call at document ready

see demo: https://jsfiddle.net/qzrfwc3g/

or do it the normal way 3 lines of code:

$("input[name='gender'],input[name='age']").on("click", function() {
     console.log($(this).val());
});



回答3:


I don't know why you want do it like this , as you code , I think there is a error here .

for (i in s) {
  s[i].on("click", function() {
      s[i].off();
      console.log(this.getAttribute('value'))
   });
}

You declare i as global , when event fires , i refers the same value .You can try this :

for (let i in s) {
      s[i].on("click", function() {
          s[i].off();
          console.log(this.getAttribute('value'))
       });
    }



回答4:


you are adding multiple click events to same element that why you get multiple console.log for one click. To resolve this just add a condition before assigning event listners.

var s,
    getData = {

      cacheDOM: {
        gender: $("input[name='gender']"),
        age: $("input[name='age']")
      },

      init: function() {
        if(!s){
            s = this.cacheDOM;
            this.getInput();
        }
      },

      getInput: function() {
        for (i in s) {
          s[i].on("click", function() {
            s[i].off();
            console.log(this.getAttribute('value'))
          });
        }
      },
    };


来源:https://stackoverflow.com/questions/39652419/javascript-click-events-firing-multiple-times

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!