连接JQuery变量

CBB*_*CBB 0 javascript variables jquery

我需要在每个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;
});
Run Code Online (Sandbox Code Playgroud)

... 等等.我需要继续在每个元素和变量的末尾添加数字(即collegeId [number]和("#insert [number]").我尝试过循环,.append,+等等,似乎没有任何工作.

任何帮助将不胜感激!

Sta*_*nko 6

正确的方法是使用"数据" - 字段您有这样的按钮:

<button data-id="1" class="insert">
Run Code Online (Sandbox Code Playgroud)

这只是一个功能:

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

你也可以将collegeId存储在button-tag中(不要写"data-collegeId",因为数据字段不支持大写):

<button data-collegeid="1" class="insert">
Run Code Online (Sandbox Code Playgroud)

然后你得到它在一行:

var collegeId = $(this).data('collegeid');
Run Code Online (Sandbox Code Playgroud)