繁体   English   中英

函数被调用了几次?

[英]Function being called several times?

因此,我具有以下函数,该函数调用另一个函数,称为“ change_name(event,name)”。 原来'change_name'被调用了不止一次? 它使用的变量具有混合值。

function input_name(event, name) {
    event.stopPropagation();
    name.style.backgroundColor = "transparent";
    window.localStorage.removeItem("oldname");
    window.localStorage.setItem("oldname", name.value);
    $(this).click( function()
    { 

    change_name(event, name); } );

    $(name).keydown(function(event){
        if(event.keyCode == 13){
            change_name(event, name);
        }
    }); 
}


 function change_name(event, element) {
      event.stopPropagation();
      var name_input = element;
      var name = name_input.value;
      var oldname = window.localStorage.getItem("oldname");
    // new_name.innerHTML = name;
     console.log("Nombre viejo: " + oldname);
     console.log("Nombre nuevo: " + name);

 }

input_name函数是元素的属性

 input.setAttribute("onclick", "input_name(event, this);");

为什么我的价值观变得混乱? 有任何想法吗?

您将在每次input click添加一个新的clickkeydown事件。 这些事件需要添加到click事件之外。

// on click, input_name is called
input.setAttribute("onclick", "input_name(event, this);");

// this function is called on every click of input
function input_name(event, name) {

  // new events are added on every click
  $(this).click(function() {/* ? */});
  $(name).keydown(function(event) {/* ? */}); 
}

因此,请执行以下操作:

// on click, input_name is called
input.setAttribute("onclick", "input_name(event, this);");

// events are added once
$(input).click(function() {/* ? */});
$(input).keydown(function(event) {/* ? */}); 

// this function is called on every click of input
function input_name(event, name) {
  /* ? */
}

还要研究为什么使用$().click创建onclick以及input.setAttribute("onclick", ...)由于您使用的是jQuery,因此更喜欢使用$().click来设置属性。

暂无
暂无

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

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