我试图避免不同的 ID 使用相同的代码。类似submitter1、submitter2等。在同一过程中,还使用变量来获取不同位置1、不同位置2等的输入框id。有人可以帮我解决下面的代码吗?
$(document).ready(function() {
$('#submitter<--Variable Here-->').click(function(event) {
event.preventDefault();
var newlocation = $("input[name=differentlocation"<--Same Variable Here-->"']");
alert(newlocation); //testing purposes
//$('#location').val(newlocation).change(); //Changes location input box
//$("#submit").click(); //submits new location
});
});
这段代码使用静态 id 工作,但就像我说的,我想调整它以使用可变 id。
谢谢。
最佳答案
您可以使用attribute starts with selector :
$('button[id^="submitter"]').click(...);
在click
函数中,您可以使用简单的字符串方法获取id
:
var uuid = this.id.slice(9),
newlocation = $('input[name="differentlocation'+uuid+'"]');
关于Jquery 和变量 ID 名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7952022/