首页 > 解决方案 > 函数被多次调用?

问题描述

所以我有以下函数调用另一个名为'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);");

为什么我的价值观会混淆?有任何想法吗?

标签: javascriptjquery

解决方案


每次单击 时,click您都会添加一个新事件。这些事件需要添加到点击事件之外。keydowninput

// 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而不是设置属性。


推荐阅读