具有相同类的jQuery按钮,从按钮获取值

时间:2012-04-03 01:23:30

标签: php jquery html jquery-ui

我有一个PHP脚本,它为每个内容计划生成按钮。脚本echo的1个HTML按钮具有相同的名称,类和ID,但是值是基于变量设置的。

在jQuery中,我已经根据它的类声明了按钮,所以类似

$('.save').button();

然而,当我点击一个按钮时,它总是会返回第一个按钮“1”的值,即使我点击了第3个按钮或第20个按钮。

的jQuery

$('.save').unbind().click(function() {      
    $.post('create.php', {'val' : $('.save').val()}, function(data){    
       alert($('.save').val()); // Always alerts "1" regardless of button pressed.     
       });
});

PHP

$ctr = 1;
foreach($GLOBALS['conflict_schedule'] as $key => $value) {
    $html = '

    <div style="float:right;">
    <button class="save" name="save" value="' . $ctr . '" id="save">Save</button>
    </div>

    echo $html;
    $ctr++;
}

2 个答案:

答案 0 :(得分:2)

不要重新选择$('.save') - 元素,只需使用引用所点击元素的$(this)

$('.save').unbind().click(function() {
    var clicked = $(this);

    $.post('create.php', {'val' : clicked.val()}, function(data){
        alert(clicked.val());
    });
});

答案 1 :(得分:1)

对我来说,正确的答案似乎是更改PHP以生成唯一ID,而不是在所有按钮上使用相同的ID:

$ctr = 1;
foreach($GLOBALS['conflict_schedule'] as $key => $value) {
    $html = '

    <div style="float:right;">
    <button class="save" name="save" value="'.$ctr.'" id="save_'.$ctr.'">Save</button>
    </div>

    echo $html;
    $ctr++;
}

如果使用JQ 1.7+:

$('.save').on('click' create); //to bind

$('.save').off('click' create); //to unbind

function create(e) {
    $.post('create.php', {'val' : e.target.value}, function(data){    
       alert(e.target.value);
    });
}