这应该非常简单,但我无法让它工作,而且我是 Javascript 的绝对初学者。我在这里查看了各种线程。 我正在使用 django 模板,通过一个简单的链接。我想添加点击确认消息,例如“垃圾箱 (14) 项目?”你确定吗?'其中 14 是准备在表单中提交的复选框数量。现在我已经有了。
<button type="submit" class="actionbutton" name="delete" onclick="return confirm('Add projects to trash - Are you sure?')" >Remove / Add To Trash</button>
这当然没有要删除的项目数量。我可以在头部添加一个脚本来计算复选框的类,但我想知道如何在确认对话框本身内执行javascript?比如...
<button type="submit" class="actionbutton" name="delete" onclick="return confirm('Add ($(":checkbox:checked").length) to trash - Are you sure?')" >Remove / Add To Trash</button>
这不起作用,可能是因为“:checkbox:checked”在onclick“”中被转义。
有人指出我正确的方向,即做这种事情的“通常”方式是什么......
最佳答案
明智地使用引号并使用 +
创建有效的字符串
<button type="submit" class="actionbutton" name="delete" onclick="return confirm('Add (' + $(':checkbox:checked').length + ') to trash - Are you sure?')" >Remove / Add To Trash</button>
<小时/>
我建议使用不显眼的事件处理程序。添加唯一标识符,我已添加 submitbutton
作为 CSS 类
<button type="submit" class="actionbutton submitbutton" name="delete" >Remove / Add To Trash</button>
使用 Native Vanilla JS 绑定(bind)事件
document.querySelector('.submitbutton').addEventListener("click", function (event) {
var msg = 'Add (' + document.querySelectorAll('[type=checkbox]:checked').length + ') to trash - Are you sure?';
if (!confirm(msg)) {
event.preventDefault();
}
});
jQuery
$('.submitbutton').on('click', function(){
return confirm('Add (' + $(':checkbox:checked').length + ') to trash - Are you sure?')
});
关于javascript - 单击确认添加复选框长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47286526/