我在 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/