javascript - 从按钮调用 jquery 函数(不使用 onclick)

标签 javascript jquery

我在 jQuery 中创建了一个函数,用于根据特定表中的 ID 编辑数据库信息。

clickme(id);

该函数在 onclick 事件中被调用,但这似乎是一个糟糕的做法。 我调用该函数的代码是用 PHP 创建的,因此它会自动列出函数中的 ID。例如,它获取数据库并列出所有可用的 ID,根据 ID 自动创建链接:

<button ... onclick='clickme(1)'...</button>
<button ... onclick='clickme(2)'...</button>
<button ... onclick='clickme(3)'...</button>

既然这是一个不好的做法,那么我怎样才能在不使用 onclick 方法的情况下实现相同的工作方法呢? 目标是使用 sweetalert 之类的东西来:

Click the button that contains the id and call the function
Show a sweetalert to user confirm the action in the id X
Confirm and call the function
Show another sweetalert to show OK or NOK

有人可以帮我吗? 它使用 onclick 方法,但我宁愿使用另一种方法,但我不知道如果没有这种方法,如何使用我需要的“ID”调用该函数。谢谢。

最佳答案

您可以向所有按钮添加一个 EventListener,并使用从数据属性获取的数字运行其中的函数 clickme:

$("button").click(function() {
  let button = $(this); // the button you clicked
  let id = button.data("id"); // the data-id attribute of the button
  clickme(id);
});


function clickme(id) {
  console.log(`Button with id ${id} clicked`);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button data-id="1">Click Me 1</button>
<button data-id="2">Click Me 2</button>
<button data-id="3">Click Me 3</button>
<button data-id="4">Click Me 4</button>

这样您仍然可以从 PHP 控制 ID,但不会将监听器分配为属性。

按钮还可以有多个 data- 属性:

$("button").click(function() {
  let button = $(this); // the button you clicked
  let id = button.data("id"); // the data-id attribute of the button
  let fun = button.data("function");
  clickme(id, fun);
});


function clickme(id, fun) {
  console.log(`Button with id ${id} and function ${fun} clicked`);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button data-id="1" data-function="update">Click Me 1</button>
<button data-id="2" data-function="active">Click Me 2</button>
<button data-id="3" data-function="foo">Click Me 3</button>
<button data-id="4" data-function="bar">Click Me 4</button>

关于javascript - 从按钮调用 jquery 函数(不使用 onclick),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52075585/

相关文章:

javascript - 使用 JQuery 淡入 JSON ajax 列表

javascript - 将 Rails 模型参数传递给 javascript onchange 调用?

javascript - 悬停按钮下拉菜单上的 Bootstrap

jquery - 如何在一排显示更多轮播?

javascript - 发送发布请求并收到错误 "undefined is not a function"

javascript - 如何将链接作为类名的跨度转换为 <a href =""> 链接

javascript - 检查并下载条款后启用提交按钮

javascript - ERR_INVALID_ARG_TYPE错误

javascript - 为什么我的图像按钮没有打开它应该打开的链接?

javascript - React - Firebase - GoogleAuthProvider 不是构造函数