如果我用变量替换 id,下面的代码将不起作用。我尝试了不同的组合但没有成功。我正在表单元素上使用。如果有人知道如何完成这项工作,请告诉我。谢谢。
这有效:
$('#Button1, #Button2').click(function() {
//
});
这是我的示例代码,但不起作用:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Untitled Document</title>
<style>
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> <script>
$(document).ready(function(){
var Btn1 = $("#buy");
var Btn2 = $("#preview");
$(Btn1, Btn2).click(function(){ console.log("hey");})
});
</script>
</head>
<body>
<form>
<input type="button" value="Preview" id="preview" />
<input type="button" value="Buy" id="buy" />
</form>
</body>
</html>
最佳答案
您可以连接 jQuery 元素并为两者分配单击功能。
Btn1.add(Btn2).click(function(){
console.log("hey");
});
更好的解决方案是为按钮提供一些类,然后分配点击它们:
$('.myButton').click(function() {
console.log("hey");
});
关于jquery - 将相同的函数绑定(bind)到jquery中的不同元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8678821/