html - 尽管 $(document).on('click', '.foo', function) 方法,但克隆元素上的单击事件不起作用
问题描述
我有以下 div
<div class = 'step'></div>
附加到一个click()
事件,.step
如果它没有,则添加一个类,反之亦然:
$(".step").click(function(){
if ($(this).hasClass('stepLit')) {
$(this).removeClass('stepLit')
} else {
$(this).addClass('stepLit')
}
})
我像这样克隆 div:
var step = $(".step").clone()
并附加它:
$(step).appendTo('#foo')
现在,如果我想使用 class 将点击事件附加到所有现有和动态生成的 HTML 元素'.step'
,我必须使用以下.on
方法:
$(document).on('click', '.step', function(){...})
但是当我单击我的克隆+附加元素时,事件(添加/删除 lit 类)仍然没有发生。这是否与this
我的点击函数中的关键字现在不指代被点击的 div 而是指文档这一事实有关?
解决方案
我为您创建了一个演示,看看这是否适合您。
$(document).on('click', '.step', function(){
if ($(this).hasClass('stepLit')) {
$(this).removeClass('stepLit');
$(this).find('span').text('step');
} else {
$(this).addClass('stepLit');
$(this).find('span').text('stepLit');
}
});
$(document).on('click', '.clone', function(){
console.clear();
let $step = $(".step:first").clone()
console.log($step);
$step.appendTo("#foo");
});
div{
height: 50px;
}
.step{
background: aquamarine;
}
.stepLit{
background: bisque;
}
#foo{
background: burlywood;
margin: 5px 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='step'>
<span>step</span><br>
<button class="clone">Clone</button>
</div>
<div id="foo"></div>
推荐阅读
- python - pip 安装 MarkupSafe 包的 0.0.0 版本
- java - html - 如何用德语本地化 Textinput 类型编号
- html - 如何在剧作家中隐藏地址栏
- javascript - 在Angular 11中使用嵌套循环扩展表格行
- azure-devops - 在 Azure DevOps 中限制项目集合构建服务 ({OrgName}) 的访问
- actionscript-3 - 如何在actionscript 3中更改dataGrid中特定行的背景颜色
- android - 华为 EMUI 10、11 上的应用程序图标问题,只是灰色,无法显示我的应用程序图标
- r - r中的ggplot问题
- solr - Solr 是否尝试读取每个搜索请求的存储字段?
- javascript - Cordova 相机插件计时器选项未在 iPhone 上显示