表格标题上的切换按钮仅在2次切换后才起作用

时间:2015-01-19 06:55:13

标签: javascript jquery css jquery-datatables

我有一个包含搜索功能的表,单击切换按钮时,在表列标题中打开搜索输入。再次单击该按钮时,它将恢复为列名称。但是,此功能仅在两次单击后才起作用,之后会引入一些奇怪的样式,我不知道它来自哪里。

这是javascript:

$('#action_btn').on('click', function (event) {

if (document.getElementById("toggle_id").value == "OFF") {

    // Setup - add a text input to each footer cell
    $('#example thead th').each(function () {
        var title = $('#example tfoot th').eq($(this).index()).text();
        $(this).html('<input type="text" placeholder="Search ' + title + '" />');
        document.getElementById("toggle_id").value = "ON";
    });

    // DataTable
    var table = $('#example').DataTable();

    // Apply the search
    table.columns().eq(0).each(function (colIdx) {
        $('input', table.column(colIdx).header()).on('keyup change', function () {
            table.column(colIdx)
                .search(this.value)
                .draw();
        });
    });

} else {
    // Remove a text input to each footer cell
    $('#example thead th').each(function () {
        var title = $('#example tfoot th').eq($(this).index()).text();
        $(this).html('<th>'+title+'</th>');
        document.getElementById("toggle_id").value = "OFF";
    });
}
});

我有一个小提琴,可以更轻松地查看我的代码:http://jsfiddle.net/flldom001/vmxgz0s5/

如何确保该按钮以下列方式切换搜索?: 默认值:关闭 切换:开/关

2 个答案:

答案 0 :(得分:2)

我在你的小提琴中做了一些改变

我删除了表格外的#toggle_id div,并提供了data-value属性。

选中此DEMO

$(document).on('click', '#action_btn', function (event) {

    if ($("#toggle_id").attr("data-value") == "OFF") {
        console.log($("#toggle_id").data("value"));
        // Setup - add a text input to each footer cell
        $('#example thead th').each(function () {
            var title = $(this).text().replace('Search ', '');
            $(this).html('<input type="text" placeholder="Search ' + title + '" />');
            $("#toggle_id").attr("data-value", "ON");
        });

        // DataTable
        var table = $('#example').DataTable();

        // Apply the search
        table.columns().eq(0).each(function (colIdx) {
            $('input', table.column(colIdx).header()).on('keyup change', function () {
                table.column(colIdx)
                    .search(this.value)
                    .draw();
            });
        });

    } else {
        // Setup - remove a text input to each footer cell
        $('#example thead th').each(function () {
            var title = $(this).find('input').attr('placeholder');             
            $(this).removeAttr('class tabindex aria-controls rowspan colspan aria-sort aria-label style').html(title);
            $("#toggle_id").attr("data-value", "OFF");
        });
    }
});

答案 1 :(得分:0)

不使用div标签上的 value 属性,而是使用 class 属性。根据需要切换此属性。

由于不是div的有效属性,因此DOM不会选择它。明确将属性设置为&#39; ON&#39;或者&#39; OFF&#39;。它选择了。

这是更新的fiddle

toggle_id元素

<div id="toggle_id" class="OFF">

Jquery检查开/关状态

if ($("#toggle_id.OFF").length > 0) {
相关问题