如何清理这个jQuery函数并使其更加灵活
How can this jQuery function be cleaned up and made more flexible?
这是我的函数:
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
/.hide
与if
/else
子句一起使用 - 您可以像
var a = 1, b = 2
一样链接var
- 您可能想要使用
===
来避免JavaScript的怪癖 - 您可以使用
$(...).each
而不是$.each($(...)
相关文章:
- jQuery GraphML解析(正在清理导入的数据)
- 如何清理此jQuery代码
- 如果我动态创建jquery UI对话框,除了在单页应用程序中调用对话框(“关闭”)之外是否有任何清理
- 使用jQuery面临“html”清理挑战
- jQuery.queue() 与使用回调函数完成某事有何不同
- 在复选框单击时清理我的jQuery代码
- 如何避免在巨大的 ajax 页面上进行 Jquery 解析/清理
- jQuery 清理或更好的方法
- JQuery:图像源变量清理
- 如何清理这个jQuery函数并使其更加灵活
- 为什么要使用 jQuery $(window).ready(),它与 $(window).load() 有何不同
- 使用Javascript或jQuery清理所见即所得编辑器的HTML输出
- 清理javascript/jquery中的字符串
- Jquery -动态按钮,我可以清理这个
- jQuery或Javascript正则表达式清理url中的日期参数
- 分离,通过jQuery清理data-attribute中的标记
- jQuery$.data()方法与直接将变量附加到DOM元素有何不同
- 带有负载的jQuery对话框本身不会清理
- 在验证之前清理jQuery验证插件数据
- Jquery和JS从何而来?