如何将onclick事件添加到动态生成的按钮并显示/隐藏表

时间:2014-04-25 03:59:18

标签: javascript php jquery html html-table

我有很多按钮根据最终用户请求动态生成

$out='<input class="show_hide" type="button" id="'.$platform_name.'" value="'.$platform_name.'"/>';

同样的变量名表也是动态的

$out.='<table id="'.$platform_name.'" > </table>

如果设置按钮

<input class="show_hide" type="button" id="button1'" value="button1"/> 
<table id="button1" > </table>

如何获取按钮名称/ id的数量,并基于按钮名称/ id查找表并显示/隐藏表格。请帮我。我更新鲜的PHP

5 个答案:

答案 0 :(得分:3)

在动态绑定方面,请代表

$( "body" ).on( "click", ".show_hide", function() {
    $( this ).next().toggle();
});

或者您可以在兄弟选择中提供选择器

$( "body" ).on( "click", ".show_hide", function() {
    $( this ).next("#table1").toggle();
});

此代码将隐藏/显示下一个兄弟(在您的情况下是一个表格),点击按钮show_hide

答案 1 :(得分:0)

id在HTML中应该是唯一的。 E.g。

<input class="show_hide" type="button" id="button1'" value="button1"/> 
<table id="table1"></table>

然后,你可以选择&#39;使用jQuery的按钮或表:

$('#button1')
$('#table1')

E.g。

for (var i = 1; i <= numberOfTables; i++) {
    $('#button' + i).click(function() {
        $('#table' + i).hide();
    });
}

答案 2 :(得分:0)

如果你想动态地向元素添加事件处理程序,请确保你可以拥有该元素的id,你可以使用普通的javascript,

elemm.onclick = function() { alert('blah'); };

其中elemm = document.getElementById("button1")

答案 3 :(得分:0)

尝试使用委托:

所有按钮点击事件:

$(document).on( ".show_hide", "click", function() {
 //all button click
})
表的

使用wildcart:

   $(document).on( "[id^=table]", "click", function() {
     //all table click
    })

你也可以像这样使用wildcart按钮:

 $(document).on( "[id^=button]", "click", function() {
         //all table click
        })

答案 4 :(得分:0)

正如其他人所说,id必须是唯一的。您的按钮和表格不能具有相同的ID。但您可以使用按钮的值来查找关联表:

$out='<input class="show_hide" type="button" value="'.$platform_name.'"/>';

由于按钮是动态的,您不知道所有按钮的ID,但您可以使用jQuery类选择器查找具有show_hide类的所有按钮,并将函数应用于click事件:

$("input.show_hide").on('click', function () {
    // get the id of the table associated with the button
    var tableId = $(this).val(),

    // toggle your table between hide and shown
    $("#" + tableId).toggle();

});

如果您的表格可以在页面加载后动态添加,则必须使用委托来定义点击事件:

$(document).on( ".show_hide", "click", function() {
    .. same code goes here
});
相关问题