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">

そして、このすべてのたわごとのためのたった1つの関数:

$('.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 に答える