jquery按钮事件


jquery button event on multiple buttons with the same class

我的按钮有问题。

使用php,我正在设置按钮的名称,所以事先不知道按钮的名称是什么。然而,按钮有一个类,但有多个按钮。当我点击其中一个按钮时,所有按钮都会触发它们的事件,因为它们都有相同的类。

有没有一种方法可以让我只按一个按钮启动事件?这是我的代码:

    <button class="delad" name="<?php print $user; ?>">Delete this ad? </button>
<script>
$(document).ready(function()
{
    count = 0;
    if(count == 0)
    $(".delad").click(function(e)
    {
        e.stopPropagation() 
        v1 =$(this).attr('name');
        sum = {'v1': v1};
        sum = JSON.stringify(sum);
        $.ajax(
                {
                    url: 'del_ad.php',
                     data: 'json='+ sum,
                    success: function(data) 
                    {
                        alert(data)
                    }
                });
                count += 1;
    });
});
</script>

尝试以下操作:

<button id="dino" class="delad" name="<?php print $user; ?>">Delete this ad? </button>
<script>
$(document).ready(function()
{
count = 0;
if(count == 0)
$("#dino").click(function(e)
{
    e.stopPropagation() 
    v1 =$(this).attr('name');
    sum = {'v1': v1};
    sum = JSON.stringify(sum);
    $.ajax(
            {
                url: 'del_ad.php',
                 data: 'json='+ sum,
                success: function(data) 
                {
                    alert(data)
                }
            });
            count += 1;
});

});

我不知道这是否实用,但这取决于你有多少按钮。

正如你在下面的代码中看到的那样,你可以测试一下点击了哪个按钮,然后对其应用适当的功能。

我认为这将适用于你提供的信息,即使我假设按钮在页面上的位置将适合某个功能,无论它的名称如何。

$(".delad").on("click", function(){
    var btnName = $(this).attr("name");
    if($(btnName) == <?php echo $nameOfButton1;?>){
        //do something thats specific 
        //to the button with this name
    }else if($(btnName) == <?php echo $nameOfButton2;?>){
        //do something thats specific 
        //to the button with this name
    }else if($(btnName) == <?php echo $nameOfButton3;?>){
        //do something thats specific 
        //to the button with this name
    }
});

希望这能帮助

您可以通过使用"this"来确定单击了哪个按钮,通过"this"可以访问html对象的属性。

$(document).ready(function(){
    $("input[class='my_class']").click(function(){ //get all button with the class of 'myclass'
        alert($(this).attr('name')); //'this' determines which button was clicked
        //ajax call
    });
});

请参见此示例:)http://jsfiddle.net/silkherb/o7qpehwg/2/

我也遇到过这种情况,问题是脚本被调用了多次(在循环中)!

把这个放在那里,以防有人遇到同样的问题。