具有相同类的多个按钮上的jquery按钮事件

时间:2014-10-22 06:42:57

标签: javascript php jquery

我无法使用按钮。

使用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>

4 个答案:

答案 0 :(得分:0)

尝试以下方法:

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

});

});

答案 1 :(得分:0)

您可以使用&#39;这个&#39;来确定点击了哪个按钮。你可以访问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/

答案 2 :(得分:0)

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

正如您在下面的代码中所看到的,您将测试以查看单击了哪个按钮,然后将函数approriate应用于该按钮。

我认为即使我假设页面上按钮的位置与某个功能相关,无论其名称是什么,这都会对您提供的信息有用。

$(".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
    }
});

希望这有帮助

答案 3 :(得分:0)

这件事发生在我身上,问题是脚本被多次调用(在一个循环中)!

只是把它放在那里以防有人遇到同样的问题。

相关问题