我想编写一个事件监听器函数,当我的 <ul>
中的任何元素出现时需要调用该函数。标签被编辑。
例如对于给定 ul 中的元素
<ul class="container">
<h4 contenteditable="true">hi</h4>
<h5 contenteditable="true">hi</h5>
<label>
<input id="indeterminate-checkbox" type="checkbox" />
<span contenteditable="true">Indeterminate Style</span>
</label>
<p contenteditable="true">hi</p>
<blockquote contenteditable="true">sup</blockquote>
</ul>
我想使用element.addEventListener()
仅一次(我不能只为 ul
声明 contenteditable 并添加监听器,因为这会产生不需要的 UI 更改)。另外,如果可能的话我想声明 onchange
一次获取所有这些元素(就像来自 css)。
我想这样做是因为我正在动态添加元素并希望删除冗余代码。
最佳答案
看看这里的第二个答案:trigger an event when contenteditable is changed 您可以对 ul 内的所有可内容编辑元素执行此操作
$( "ul.container" ).on( "focus", "[contenteditable=true]", function() {
//here you save the content innerhtml/text, etc of the element
});
然后通过“模糊”事件,当您离开一个元素时,您可以测试旧内容是否相同,然后执行一些操作。 有关“on”jquery 函数的引用:http://api.jquery.com/on/
关于javascript - 如何一次为特定标签中的所有元素编写事件监听器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52525014/