javascript - 函数被多次调用?
问题描述
所以我有以下函数调用另一个名为'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);");
为什么我的价值观会混淆?有任何想法吗?
解决方案
每次单击 时,click
您都会添加一个新事件。这些事件需要添加到点击事件之外。keydown
input
// 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
而不是设置属性。
推荐阅读
- function - decimalToBinary 函数的输入是什么
- android - addToBackStack 没有导航回正确的片段
- android - Android LEANBACK 库定制
- java - 如何使用 class.forName("int[][][]") 获取课程?
- sql - 在发票表上添加汇总行的查询(按单个发票汇总)
- apache-spark - Apache SPARK:哪些 SQL 操作只能由 Spark 通过将所有数据移动到一个分区来执行?
- google-apps-script - 用于谷歌表单的谷歌应用脚本在响应表的相同列中创建了多选网格
- sharepoint - 从 Salesforce 中的 Sharepoint 下载 zip 文件
- php - 使用 laravel 在用户注册表单中填充选择菜单
- go - 从 protos 生成的结构提供了我无法使用的指针