javascript - JQuery 关闭按钮事件处理程序
问题描述
我有五个buttons
带有引导程序close
,我将onclick
事件处理程序添加到alert()
下一个兄弟文本。问题是它只显示alert()
在第一个关闭按钮上。
<script>
$("#closenotify").click(function(){
alert($(this).next().text());
});
</script>
我是 JQuery 的新手,让我知道我在这里缺少什么?
谢谢
解决方案
这是因为您使用的 ID 是唯一的,所以 jQuery 会在它找到的第一个 ID 处停止。继续并更改您的代码以使用一个类,它将起作用。您已经close
为每个类添加了一个类,因此只需将其更改为以下内容。
附带说明一下,您的 jsFiddle 中有几个额外的结束div
标记。
解决方案
$(".close").click(function(){
alert($(this).next().text());
});
工作演示
$(".close").click(function(){
alert($(this).next().text());
});
.alert-purple { border-color: #694D9F;background: #694D9F;color: #fff; }
.alert-info-alt { border-color: #B4E1E4;background: #81c7e1;color: #fff; }
.alert-danger-alt { border-color: #B63E5A;background: #E26868;color: #fff; }
.alert-warning-alt { border-color: #F3F3EB;background: #E9CEAC;color: #fff; }
.alert-success-alt { border-color: #19B99A;background: #20A286;color: #fff; }
.glyphicon { margin-right:10px; }
.alert a {color: gold;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-md-12">
<div class="alert alert-purple alert-dismissable">
<span class="glyphicon glyphicon-certificate"></span>
<button type="button" id="closenotify" class="close" data-dismiss="alert" aria-hidden="true">
×</button><strong>sagsagsagsagsag</strong>
</div>
</div>
<div class="col-md-12">
<div class="alert alert-purple alert-dismissable">
<span class="glyphicon glyphicon-certificate"></span>
<button type="button" id="closenotify" class="close" data-dismiss="alert" aria-hidden="true">
×</button><strong>fdsggsdgsdgsdg</strong>
</div>
</div>
<div class="col-md-12">
<div class="alert alert-purple alert-dismissable">
<span class="glyphicon glyphicon-certificate"></span>
<button type="button" id="closenotify" class="close" data-dismiss="alert" aria-hidden="true">
×</button><strong>sgaasgsagsaggasg</strong>
</div>
</div>
<div class="col-md-12">
<div class="alert alert-purple alert-dismissable">
<span class="glyphicon glyphicon-certificate"></span>
<button type="button" id="closenotify" class="close" data-dismiss="alert" aria-hidden="true">
×</button><strong>This is a test nigga</strong>
</div>
</div>
<div class="col-md-12">
<div class="alert alert-purple alert-dismissable">
<span class="glyphicon glyphicon-certificate"></span>
<button type="button" id="closenotify" class="close" data-dismiss="alert" aria-hidden="true">
×</button><strong>This is a test nigga</strong>
</div>
</div>
文档
https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/id
推荐阅读
- swift - 简单的 Int() 类型转换需要 110 毫秒的 Swift 类型检查
- python - 从索引列中的行中提取最后一个单词
- python - 如何在 Pandas 中覆盖 .csv 文件?
- project-reactor - Reactive Java OneError 恢复错误处理
- python - 循环此数据框的更有效方法?
- json - Jackson 2.8 中有没有办法将空值序列化为空字符串
- python-3.x - 如何在python中返回函数的值
- r - 强制执行 R 中的列表项
- javascript - Sequelize js,我们如何在迁移中更改列类型
- python - 通过 Python 3 插入 MySQL 时保留特殊字符