简体   繁体   English

jQuery click事件触发多次

[英]jQuery click event triggers more than once

I'm doing a project with contains a simple form that the user must fill and then a button to submit it. 我正在做一个项目,其中包含用户必须填写的简单表单,然后单击按钮提交。 The first time you click on the button the event (called by .click()) happens correctly, but the second time the event happens twice, and so on.. if I have submit my form 100 times it would play the event 100 times. 第一次单击该按钮时,事件(由.click()调用)正确发生,但是第二次该事件发生两次,依此类推..如果我提交了100次表单,它将事件100次。

function MenuOpinion(){
$("#registraropinion").click(IngresarOpinion);
}

function IngresarOpinion(){ 
var seleccionada= $("#perpelicula option:selected").html();
if(seleccionada=="Seleccione"){
    $("#error_opinion").html("Seleccione una película de la lista");
}else{
    $("#error_opinion").html("");
    var nuevaOpinion=[];
    nuevaOpinion['nombre']=$("#pernombre").val();
    nuevaOpinion['edad']=$("#peredad").val();
    nuevaOpinion['opinion']=$("#peropinion").val();
    nuevaOpinion['puntaje']= parseInt($("#puntaje option:selected").html());
    nuevaOpinion['aclaracion']=$("#txtaclaracion").val();
    for(var i=0; i<listaPeliculas.length; i++){
        if(listaPeliculas[i]['titulo']==seleccionada){
            listaPeliculas[i]['opiniones'].push(nuevaOpinion);
        }
    }
    /*Aviso al usuario y vuelvo al inicio*/
    alert("Opinión guardada");
    $("#opinion").hide();
    $("#inicio").show();
}
}

I'm really can't find the problem. 我真的找不到问题。 I leave the code that has to do with this button. 我留下与此按钮有关的代码。

Change 更改

function MenuOpinion(){
$("#registraropinion").click(IngresarOpinion);
}

to

$(function(){ // <-- on document ready
   $("#registraropinion").click(IngresarOpinion); // <-- bind the click event once on dom ready
}}

My guess is you are running MenuOpinion() on each submit - causing it to bind another click handler to your element - so 100th click will trigger all 100 click event handlers bound to your element 我的猜测是您正在每个提交上运行MenuOpinion()-导致它将另一个单击处理程序绑定到您的元素-因此第100次单击将触发绑定到您元素的所有100个单击事件处理程序

If you are using a form and a submit button then you should use 如果您使用的是表单和提交按钮,则应使用

$(function(){ //<-- on document ready
   $(yourform).submit(IngresarOpinion); // <-- bind the click event
}}

then have an e.preventDefault inside the function 然后在函数内部有一个e.preventDefault

function IngresarOpinion(e){
     e.preventDefault();
     // rest of your code
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM