如何清理这个jQuery函数并使其更加灵活

How can this jQuery function be cleaned up and made more flexible?

本文关键字:何清理 jQuery 函数      更新时间:2023-09-26

这是我的函数:

function DisplayGridElementsBasedOnCriteria(dataItem, propertyToEvaluate, shouldEqualvalue, selectorsToChange, hideSelectedElements, nameOfColumnContainingElements) {
if (propertyToEvaluate == shouldEqualvalue) {
    var $row = $(dataItem.row);
    if (nameOfColumnContainingElements == undefined) {
        if (hideSelectedElements) {
            $row.children("td").children(selectorsToChange).hide();
        }else {
            $row.children("td").children(selectorsToChange).show();
        }
    } else {
        $.each($row.children("td"), function (index, column) {
            var $column = $(column);
            var $headerText = $column.closest('table').find('th').eq($column.index()).children(".t-link").text();
            if ($headerText == nameOfColumnContainingElements) {  
                if (hideSelectedElements) {
                    $column.children(selectorsToChange).hide();
                } else {
                    $column.children(selectorsToChange).show();
                }
            }
        });
    }
}

}

正在以这样的方式使用:

 <script type="text/javascript">
    function onRowDataBound(e) {
        DisplayGridElementsBasedOnCriteria(e, e.dataItem.Status, "Submitted", "a.t-grid-delete, a.t-grid-Edit", true, "Actions");
    }
</script>

我不太擅长jQuery/javascript,它按照我想要的方式工作,但它看起来有点复杂和臃肿。

有人能提供一个更干净的版本吗?

根据这里的答案是更清洁的版本:

function DisplayGridElementsBasedOnCriteria(dataItem, propertyToEvaluate, shouldEqualvalue, selectorsToChange, hideSelectedElements, nameOfColumnContainingElements) {
if (propertyToEvaluate === shouldEqualvalue) {
    var $row = $(dataItem.row);
    if (nameOfColumnContainingElements === undefined) {
            $row.children("td").children(selectorsToChange).toggle(!hideSelectedElements);
    } 
    else {
        $row.children("td").each(function (index, column) {
            var $column = $(column),
                $headerText = $column.closest('table').find('th').eq($column.index()).children(".t-link").text();
            if ($headerText === nameOfColumnContainingElements) {  
                    $column.children(selectorsToChange).toggle(!hideSelectedElements);
            }
        });
    }  
}

}

至于清理:

  • 您可以将.toggle(bool)而不是.show/.hideif/else子句一起使用
  • 您可以像var a = 1, b = 2一样链接var
  • 您可能想要使用===来避免JavaScript的怪癖
  • 您可以使用$(...).each而不是$.each($(...)