Javascript Bootstrap onClick 按钮事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12081640/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:04:20  来源:igfitidea点击:

Bootstrap onClick button event

javascriptjquery-events

提问by JuanCB

This seems a silly question but just got bootstrap and it doesn't gives any examples on the website about adding a Javascript callback to a button...

这似乎是一个愚蠢的问题,但刚刚获得引导程序,它没有在网站上提供任何关于向按钮添加 Javascript 回调的示例......

Tried setting my button an id flag and then

尝试将我的按钮设置为 id 标志,然后

<div class="btn-group">
  <button id="rectButton" class="btn">Rectangle</button>
  <button class="btn">Circle</button>
  <button class="btn">Triangle</button>
  <button class="btn">Line</button>
  <button class="btn">Curve</button>
  <button class="btn">Pic</button>
  <button class="btn">Text</button>
  <button class="btn">Gradient</button>
</div>

I want to add a callback to Rectangle button...

我想向矩形按钮添加回调...

$('#rectButton').on('show', function (e) {
    //ACTION
})

cant get the point of bootstrap callbacks.

无法获得引导回调的重点。

All I could found on the web is oriented to Rails + Bootstrap... no bootstrap and JS only.

我在网上能找到的所有内容都是面向 Rails + Bootstrap 的……没有引导程序和 JS。

回答by moonwave99

There is no showevent in js - you need to bind your button either to the clickevent:

showjs 中没有事件 - 您需要将按钮绑定到click事件:

$('#id').on('click', function (e) {

     //your awesome code here

})

Mind that if your button is inside a form, you may prefer to bind the whole form to the submitevent.

请注意,如果您的按钮在 a 内form,您可能更愿意将整个表单绑定到submit事件。

回答by mrduncle1

If, like me, you had dynamically created buttons on your page, the

如果像我一样在页面上动态创建按钮,

$("#your-bs-button's-id").on("click", function(event) {
                       or
$(".your-bs-button's-class").on("click", function(event) {

methods won't work because they only work on current elements (not future elements). Instead you need to reference a parent item that existed at the initial loading of the web page.

方法将不起作用,因为它们仅适用于当前元素(而非未来元素)。相反,您需要引用在网页初始加载时存在的父项。

$(document).on("click", "#your-bs-button's-id", function(event) {
                       or more generally
$("#pre-existing-element-id").on("click", ".your-bs-button's-class", function(event) {

There are many other references to this issue on stack overflow hereand here.

此处此处的堆栈溢出中还有许多其他关于此问题的参考。