0

我需要在每个 javascript 变量和 JQuery 元素的末尾添加一个数字。

这是我的代码:

$("#insert1").click(function(){
    var collegeId1=$("#collegeId1").val();
     $.post('insert.php', {collegeId: collegeId1});
    return false;
});

$("#insert2").click(function(){
    var collegeId2=$("#collegeId2").val();
    $.post('insert.php', {collegeId: collegeId2});
    return false;
});

... 等等。我需要继续在每个元素和变量的末尾添加数字(即,collegeId[number] 和(“#insert[number]”)。我尝试了循环、.append、+ 等,但似乎没有任何效果。

任何帮助将不胜感激!

4

2 回答 2

6

正确的方法是使用“数据”字段你有这样的按钮:

<button data-id="1" class="insert">

所有这些狗屎只有一个功能:

$('.insert').click(function(){
    var id = $(this).data('id');
    var collegeId = $('#collegeId' + id).val();
    $.post('insert.php', {collegeId: collegeId});
    return false;
});

您也可以将collegeId 存储在按钮标签中(不要写“data-collegeId”,因为数据字段不支持大写):

<button data-collegeid="1" class="insert">

然后你在 1 行得到它:

var collegeId = $(this).data('collegeid');
于 2013-10-03T05:00:19.430 回答
0

如果您必须使用已有的标记,请试试这个...

$('[id^="insert"]').filter(function() {
    return /insert\d+$/.test(this.id); // filter to make sure the id matches /insert\d+/
}).on('click', function(e) {
    e.preventDefault();
    var i = /\d+$/.exec(this.id)[0], // fetch index from id
        collegeId = $('#collegeId' + i).val();
    $.post('insert.php', {collegeId: collegeId});
})';
于 2013-10-03T04:57:10.730 回答