草庐IT

javascript - 添加事件监听器后函数运行次数过多

coder 2025-01-14 原文

我构建了一个简单的演示 ( https://codepen.io/anon/pen/VgKQoq ),展示了单击按钮时创建的元素和对象:它创建了一个元素,然后将该元素的对象插入“对象”数组。当点击移除按钮时,元素和对象被成功地使用 ids 移除。

但是,问题在于每次移除一个元素时,remove 函数有时会根据点击的是哪个元素运行太多次,我也不知道为什么。在演示中,打开 javascript 控制台,创建例如 4 个元素,然后通过单击删除删除第三个元素,您将看到发生了什么。

有人知道为什么会这样吗?我认为这可能是因为事件监听器被一次又一次地添加到相同的元素中,但是在删除时它似乎不起作用。如有任何解释和最佳做法,我们将不胜感激,谢谢。

var id = 0, objects = [], removes;

function createEntry() {
	id++;

	// create new element, append to #container & create new object
	var container = document.querySelector('#container'),
	    newEntry = document.createElement("div"),
	    title = 'title text here',
	    description = 'description text here',
	    remove = 'remove',
	    dataId = id,
	    obj = new Entry(title, description, remove);
	newEntry.classList.add("entry");
	newEntry.innerHTML = '<span class="title">' + title + '</span><span class="description">' + description + '</span><span class="remove">' + remove + '</span>';
	container.appendChild(newEntry);
	newEntry.setAttribute('data-id', id);

	updateElements();

	// constructor & push into array
	function Entry(title, description, remove) {
		this.title = title;
		this.description = description;
		this.remove = remove;
		this.id = id;

		objects.push(this);
	}

	// tests
	console.log('JSON.stringify(obj): ' + JSON.stringify(obj));
	console.log('obj.id: ' + obj.id);

	function updateElements() {
		removes = document.querySelectorAll(".remove");
		listenForRemoves();

		function listenForRemoves() {
			for (let remove of removes) {
				remove.removeEventListener("click", removeElements);
				remove.addEventListener("click", removeElements);
			}
		}

		function removeElements() {
			let removedId = this.parentNode.getAttribute('data-id'),
			    objToRemove = objects.find(obj => obj.id == removedId); // not used

			this.parentNode.remove(); console.log('removed id ' + removedId);
				console.log('objects before: '); for (let object of objects) { console.log(JSON.stringify(object))};
				objects = objects.filter(obj => obj.id != removedId); // doesn't use objToRemove
				console.log('objects now: '); for (let object of objects) { console.log(JSON.stringify(object))};
		}
	}
	// works but why the repeating console logs twice?
}
button { display: block }
.entry {
	width: 100%;
	display: block;
	padding: 10px;
	border: 1px solid #f5f5f5;
}
span {
  display: block;
  width: 100%;
}
section { background: lightgreen }
<button id='btn' onclick='createEntry()'>Create</button>
<section id='container'></section>

更新:还有其他想法吗?我添加了 remove.removeEventListener("click", removeElements);,它现在摆脱了很多重复项,但它现在仍然只有两次控制台日志(好吧......有时!?)。上面更新了新的代码笔链接

最佳答案

我不确定到底发生了什么,但所有这些函数都嵌套在 createEntry 函数中。尝试将它们移到该函数之外。这似乎解决了我测试中的问题:

var id = 0, objects = [], removes;

function createEntry() {
    id++;

    // create new element, append to #container & create new object
    var container = document.querySelector('#container'),
        newEntry = document.createElement("div"),
        title = 'title text here',
        description = 'description text here',
        remove = 'remove',
        dataId = id,
        obj = new Entry(title, description, remove);
    newEntry.classList.add("entry");
    newEntry.innerHTML = '<span class="title">' + title + '</span><span class="description">' + description + '</span><span class="remove">' + remove + '</span>';
    container.appendChild(newEntry);
    newEntry.setAttribute('data-id', id);

    updateElements();

    // constructor & push into array
    function Entry(title, description, remove) {
        this.title = title;
        this.description = description;
        this.remove = remove;
        this.id = id;

        objects.push(this);
    }

    // tests
    console.log('JSON.stringify(obj): ' + JSON.stringify(obj));
    console.log('obj.id: ' + obj.id);
}

function updateElements() {
  removes = document.querySelectorAll(".remove");
  listenForRemoves();

  function listenForRemoves() {
    for (let remove of removes) {
      remove.removeEventListener("click", removeElements);
      remove.addEventListener("click", removeElements);
    }
  }


}
function removeElements(e) {
  let removedId = this.parentNode.getAttribute('data-id'),
      objToRemove = objects.find(obj => obj.id == removedId); // not used

  this.parentNode.remove(); console.log('removed id ' + removedId);
    console.log('objects before: '); for (let object of objects) { console.log(JSON.stringify(object) + " " + e.target)};
    objects = objects.filter(obj => obj.id != removedId); // doesn't use objToRemove
    console.log('objects now: '); for (let object of objects) { console.log(JSON.stringify(object))};
}

关于javascript - 添加事件监听器后函数运行次数过多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54421367/

有关javascript - 添加事件监听器后函数运行次数过多的更多相关文章

  1. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  2. ruby - 我需要将 Bundler 本身添加到 Gemfile 中吗? - 2

    当我使用Bundler时,是否需要在我的Gemfile中将其列为依赖项?毕竟,我的代码中有些地方需要它。例如,当我进行Bundler设置时:require"bundler/setup" 最佳答案 没有。您可以尝试,但首先您必须用鞋带将自己抬离地面。 关于ruby-我需要将Bundler本身添加到Gemfile中吗?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/4758609/

  3. ruby - 如何每月在 Heroku 运行一次 Scheduler 插件? - 2

    在选择我想要运行操作的频率时,唯一的选项是“每天”、“每小时”和“每10分钟”。谢谢!我想为我的Rails3.1应用程序运行调度程序。 最佳答案 这不是一个优雅的解决方案,但您可以安排它每天运行,并在实际开始工作之前检查日期是否为当月的第一天。 关于ruby-如何每月在Heroku运行一次Scheduler插件?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/8692687/

  4. ruby - 将 Bootstrap Less 添加到 Sinatra - 2

    我有一个ModularSinatra应用程序,我正在尝试将Bootstrap添加到应用程序中。get'/bootstrap/application.css'doless:"bootstrap/bootstrap"end我在views/bootstrap中有所有less文件,包括bootstrap.less。我收到这个错误:Less::ParseErrorat/bootstrap/application.css'reset.less'wasn'tfound.Bootstrap.less的第一行是://CSSReset@import"reset.less";我尝试了所有不同的路径格式,但它

  5. ruby-on-rails - 如何在 ruby​​ 中使用两个参数异步运行 exe? - 2

    exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby​​中使用两个参数异步运行exe吗?我已经尝试过ruby​​命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何ruby​​gems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除

  6. ruby - 无法运行 Rails 2.x 应用程序 - 2

    我尝试运行2.x应用程序。我使用rvm并为此应用程序设置其他版本的ruby​​:$rvmuseree-1.8.7-head我尝试运行服务器,然后出现很多错误:$script/serverNOTE:Gem.source_indexisdeprecated,useSpecification.Itwillberemovedonorafter2011-11-01.Gem.source_indexcalledfrom/Users/serg/rails_projects_terminal/work_proj/spohelp/config/../vendor/rails/railties/lib/r

  7. ruby - 续集在添加关联时访问many_to_many连接表 - 2

    我正在使用Sequel构建一个愿望list系统。我有一个wishlists和itemstable和一个items_wishlists连接表(该名称是续集选择的名称)。items_wishlists表还有一个用于facebookid的额外列(因此我可以存储opengraph操作),这是一个NOTNULL列。我还有Wishlist和Item具有续集many_to_many关联的模型已建立。Wishlist类也有:selectmany_to_many关联的选项设置为select:[:items.*,:items_wishlists__facebook_action_id].有没有一种方法可以

  8. ruby - 在没有 sass 引擎的情况下使用 sass 颜色函数 - 2

    我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re

  9. ruby - Sinatra:运行 rspec 测试时记录噪音 - 2

    Sinatra新手;我正在运行一些rspec测试,但在日志中收到了一堆不需要的噪音。如何消除日志中过多的噪音?我仔细检查了环境是否设置为:test,这意味着记录器级别应设置为WARN而不是DEBUG。spec_helper:require"./app"require"sinatra"require"rspec"require"rack/test"require"database_cleaner"require"factory_girl"set:environment,:testFactoryGirl.definition_file_paths=%w{./factories./test/

  10. ruby-on-rails - 在 ruby​​ 中使用 gsub 函数替换单词 - 2

    我正在尝试用ruby​​中的gsub函数替换字符串中的某些单词,但有时效果很好,在某些情况下会出现此错误?这种格式有什么问题吗NoMethodError(undefinedmethod`gsub!'fornil:NilClass):模型.rbclassTest"replacethisID1",WAY=>"replacethisID2andID3",DELTA=>"replacethisID4"}end另一个模型.rbclassCheck 最佳答案 啊,我找到了!gsub!是一个非常奇怪的方法。首先,它替换了字符串,所以它实际上修改了

随机推荐