jQuery 编程风格?

发布于 2024-10-10 01:38:50 字数 3933 浏览 3 评论 0原文

最近,我被要求修复一个我以前从未参与过的网站上的一些内容。我并没有真正使用 jQuery 那么多,但我想我应该看一下,看看是否可以修复它。

我已经设法解决了大部分问题,但我仍然对他们选择构建这个网站的方式感到震惊。

在文档加载时,它们用相同的大量函数替换每个锚标记和表单元素的 click() 方法。单击时,该函数会检查标签是否具有几个不同属性(甚至是非标准属性)之一,并根据存在的属性及其值执行各种不同的任务。

有些超链接有一个名为“ajaxrel”的属性,这使得 click() 函数查找另一个(隐藏的)超链接,其 ID 由 ajaxrel 属性指定,然后调用该其他超链接的 click() 函数(该超链接是也通过相同的 click() 函数进行修改)。

在服务器端,所有的 php 文件都相当长并且完全没有缩进。

整个网站的调试简直就是一场噩梦。这是标准的 jQuery 实践吗?这个导航方案看起来很糟糕。还有其他人实际上以这种方式使用 jQuery 吗?我想开始将它合并到我的项目中,但是查看这个网站让我非常头疼。

这是超链接的 click() 函数:

function ajaxBoxA(theElement, urltosend, ajaxbox, dialogbox) {

if ($(theElement).attr("href") != undefined)
      var urltosend = $(theElement).attr("href");
if ($(theElement).attr('toajaxbox') != undefined)
      var ajaxbox = $(theElement).attr('toajaxbox');

// check to see if dialog box is called for.
if ($(theElement).attr('dialogbox') != undefined)
      var dialogbox = $(theElement).attr('dialogbox');

var dodialog = 0;
if (dialogbox != undefined) {
    // if dialogbox doesn't exist, then flag to create dialog box.
    var isDiaOpen = $('[ajaxbox="' + ajaxbox + '"]').parent().parent().is(".ui-dialog-container");
    dodialog = 1;
    if (isDiaOpen) {
        dodialog = 0;
    }
    dialogbox = parseUri(dialogbox);
    dialogoptions = { close: function () { 
//          $("[id^=hierarchy]",this).NestedSortableDestroy();
        $(this).dialog('destroy').remove() 
    } };
    for ( var keyVar in dialogbox['queryKey'] )
              eval( "dialogoptions." + keyVar + " = dialogbox['queryKey'][keyVar]");
};


$("body").append("<div id='TB_load'><img src='"+imgLoader.src+"' /></div>");
$('#TB_load').show();
if (urltosend.search(/\?/) > 0) {
    urltosend = urltosend + "&-ajax=1";
} else {
    urltosend = urltosend + "?-ajax=1";
}
if ($('[ajaxbox="' + ajaxbox + '"]').length) {
  $('[ajaxbox="' + ajaxbox + '"]').each( function () { $(this).empty(); });
};
$.ajax({
    type: "GET",
    url: urltosend,
    data: "",
    async: false,
    dataType: "html",
    success: function (html) {
        var re = /^<toajaxbox>(.*?)<\/toajaxbox>+(.*)/;
        if (re.test(html)) { 
            var match = re.exec(html);
            ajaxbox = match[1];
            html = Right(html, String(html).length - String(match[1]).length);
        }
        var re = /^<header>(.*?)<\/header>+(.*)/;
        if (re.test(html)) { 
            var match = re.exec(html);
            window.location = match[1];
            return false;
        }
        if (html.length > 0) {
            var newHtml = $(html);
            if ($('[ajaxbox="' + ajaxbox + '"]').length) {
                $('[ajaxbox="' + ajaxbox + '"]').each( function () { $(this).replaceWith(newHtml).ready( function () {
                    ajaxBoxInit(newHtml)
                    if (window.ajaxboxsuccess) ajaxboxsuccess(newHtml);
                }); });
                if ($('[ajaxdialog="' + ajaxbox + '"]').length = 0) {
                    if (dodialog) $(newHtml).wrap("<div class='flora ui-dialog-content' ajaxdialog='" + ajaxbox + "' style='overflow:auto;'></div>").parent().dialog(dialogoptions);
                }
            } else {
                $("body").append(newHtml).ready( function () {
                    ajaxBoxInit(newHtml);
                    if (window.ajaxboxsuccess) ajaxboxsuccess(newHtml);
                });
                if (dodialog) $(newHtml).wrap("<div class='flora ui-dialog-content' ajaxdialog='" + ajaxbox + "' style='overflow:auto;'></div>").parent().dialog(dialogoptions);
            }
        }
        var rel = $(theElement).attr('ajaxtriggerrel');
        if (rel != undefined) $('a[ajaxrel="' + rel + '"]').click();
        tb_remove();
        return false;
    },

    complete: function () {
        $("#TB_load").remove();
        }
});
return false;

}

I was recently asked to fix something on a site which I haven't worked on before. I haven't really worked with jQuery that much, but I figured I'd take a look and see if I could fix it.

I've managed to mostly clear up the problem, but I'm still horrified at the way they chose to build this site.

On document load, they replace the click() method of every anchor tag and form element with the same massive function. When clicked, that function then checks if the tag has one of a few different attributes (non-standard attributes, even), and does a variety of different tasks depending on what attributes exist and what their values are.

Some hyperlinks have an attribute on them called 'ajaxrel', which makes the click() function look for another (hidden) hyperlink with an ID specified by the ajaxrel attribute, and then calls the click() function for that other hyperlink (which was also modified by this same click() function).

On the server side, all the php files are quite long and have absolutely no indentation.

This whole site has been a nightmare to debug. Is this standard jQuery practice? This navigation scheme seems terrible. Does anyone else actually use jQuery this way? I'd like to start incorporating it into my projects, but looking at this site is giving me a serious headache.

Here's the click() function for hyperlinks:

function ajaxBoxA(theElement, urltosend, ajaxbox, dialogbox) {

if ($(theElement).attr("href") != undefined)
      var urltosend = $(theElement).attr("href");
if ($(theElement).attr('toajaxbox') != undefined)
      var ajaxbox = $(theElement).attr('toajaxbox');

// check to see if dialog box is called for.
if ($(theElement).attr('dialogbox') != undefined)
      var dialogbox = $(theElement).attr('dialogbox');

var dodialog = 0;
if (dialogbox != undefined) {
    // if dialogbox doesn't exist, then flag to create dialog box.
    var isDiaOpen = $('[ajaxbox="' + ajaxbox + '"]').parent().parent().is(".ui-dialog-container");
    dodialog = 1;
    if (isDiaOpen) {
        dodialog = 0;
    }
    dialogbox = parseUri(dialogbox);
    dialogoptions = { close: function () { 
//          $("[id^=hierarchy]",this).NestedSortableDestroy();
        $(this).dialog('destroy').remove() 
    } };
    for ( var keyVar in dialogbox['queryKey'] )
              eval( "dialogoptions." + keyVar + " = dialogbox['queryKey'][keyVar]");
};


$("body").append("<div id='TB_load'><img src='"+imgLoader.src+"' /></div>");
$('#TB_load').show();
if (urltosend.search(/\?/) > 0) {
    urltosend = urltosend + "&-ajax=1";
} else {
    urltosend = urltosend + "?-ajax=1";
}
if ($('[ajaxbox="' + ajaxbox + '"]').length) {
  $('[ajaxbox="' + ajaxbox + '"]').each( function () { $(this).empty(); });
};
$.ajax({
    type: "GET",
    url: urltosend,
    data: "",
    async: false,
    dataType: "html",
    success: function (html) {
        var re = /^<toajaxbox>(.*?)<\/toajaxbox>+(.*)/;
        if (re.test(html)) { 
            var match = re.exec(html);
            ajaxbox = match[1];
            html = Right(html, String(html).length - String(match[1]).length);
        }
        var re = /^<header>(.*?)<\/header>+(.*)/;
        if (re.test(html)) { 
            var match = re.exec(html);
            window.location = match[1];
            return false;
        }
        if (html.length > 0) {
            var newHtml = $(html);
            if ($('[ajaxbox="' + ajaxbox + '"]').length) {
                $('[ajaxbox="' + ajaxbox + '"]').each( function () { $(this).replaceWith(newHtml).ready( function () {
                    ajaxBoxInit(newHtml)
                    if (window.ajaxboxsuccess) ajaxboxsuccess(newHtml);
                }); });
                if ($('[ajaxdialog="' + ajaxbox + '"]').length = 0) {
                    if (dodialog) $(newHtml).wrap("<div class='flora ui-dialog-content' ajaxdialog='" + ajaxbox + "' style='overflow:auto;'></div>").parent().dialog(dialogoptions);
                }
            } else {
                $("body").append(newHtml).ready( function () {
                    ajaxBoxInit(newHtml);
                    if (window.ajaxboxsuccess) ajaxboxsuccess(newHtml);
                });
                if (dodialog) $(newHtml).wrap("<div class='flora ui-dialog-content' ajaxdialog='" + ajaxbox + "' style='overflow:auto;'></div>").parent().dialog(dialogoptions);
            }
        }
        var rel = $(theElement).attr('ajaxtriggerrel');
        if (rel != undefined) $('a[ajaxrel="' + rel + '"]').click();
        tb_remove();
        return false;
    },

    complete: function () {
        $("#TB_load").remove();
        }
});
return false;

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

九公里浅绿 2024-10-17 01:38:50

绝对不是。您所描述的不是标准的jquery实践,但似乎是由于对javascript一无所知的人的糟糕设计选择造成的。

Absolutely not. What you described is not standard jquery practice, but would seem to be due to the poor design choices of someone who doesn't really know anything about javascript.

醉城メ夜风 2024-10-17 01:38:50

使用 id="" 作为链接,然后使用 jQuery 格式的 click(function() { ... });是最简单的阅读方法。

<a id="something" href="#">something here to click on</a>

<script type="text/javascript" language="javascript">
$(function () {
                 $('#something').click(function () { 
    ...
                 });
                 $('#somethingelse').click(function () { 
    ...
                 });
}
</script>

如果有人在加载 jQuery 之前单击链接(或元素),此方法不会生成错误。然后 jQuery 就可以在页面底部加载,并且页面渲染不会延迟。

Using id="" for the links and then a jQuery formated click(function() { ... }); is the easiest way to read it.

<a id="something" href="#">something here to click on</a>

<script type="text/javascript" language="javascript">
$(function () {
                 $('#something').click(function () { 
    ...
                 });
                 $('#somethingelse').click(function () { 
    ...
                 });
}
</script>

This method would not generate an error if somebody clicks on the link (or element) before jQuery is loaded. Then jQuery can be loaded on the bottom of the page and the page renders without a delay.

霊感 2024-10-17 01:38:50

他们使用 jQuery 所做的事情——使用标签上的新颖属性定制行为——并不那么疯狂,但他们的方式却相当奇怪。

我更喜欢的是根据属性将不同功能附加到不同的标签。因此,例如,如果带有 ajaxrel 属性的链接应该表现不同:

$('a[@ajaxrel]').click(function() {
    // handle click according to ajaxrel attribute
});

这至少会使代码更容易理解。 (一个问题是,如果链接具有多个这些属性,那么链接应该如何工作。)

What they're doing with jQuery — customizing behavior with novel attributes on tags — isn't so crazy, but the way they did it is rather odd.

What I would prefer is to attach different functions to different tags, depending on attributes. So, for instance, if links with the ajaxrel attribute should behave differently:

$('a[@ajaxrel]').click(function() {
    // handle click according to ajaxrel attribute
});

This would at least make grokking the code easier. (The one concern would be how links should work if they have more than one of these attributes.)

看透却不说透 2024-10-17 01:38:50

这看起来维护起来非常困难。我本人喜欢 jQuery 插件,并且总是喜欢在必要时将代码推送到插件中。

这绝对不是我开发网站和 jQuery 的方式,请不要推迟!

That seems like it would be incredibly hard to maintain. I myself love jQuery plugins and always like to push code into a plugin when necessary.

This is definitely not the way I develop websites and jQuery, please don't be put off!

⒈起吃苦の倖褔 2024-10-17 01:38:50

您所描述的不是 Jquery 标准。如果你在 Jquery 脚本上添加一行注释,任何傻瓜都可以理解你的逻辑,更不用说你了...

What you described is not a Jquery standard. If you put a single line of comment on your Jquery script, Any dummy can understand your logic, let alone you ...

雅心素梦 2024-10-17 01:38:50

看起来很糟糕,但我不想急于谈论这种风格。痛苦大多不在于所使用的风格,因为编码风格取决于依赖项、需求、API 等……痛苦几乎总是来自于糟糕的文档。至于自定义 HTML 属性,它们是有效的,例如:data-ajaxrl

It seems pretty bad, but i wouldn't like to rush and talk about the style. The pain is mostly not in the style used, as coding style depend on dependencies, requirements, APIs etc...The pain is almost always comes from poor documentation. As for custom HTML attributes they are valid ex: data-ajaxrl

美男兮 2024-10-17 01:38:50

在另一个线程中,有一些关于 jQuery 使用风格的好点: 如何组织 jQuery 代码风格以避免因如此多的括号和如此多的嵌套而造成混乱?有什么好的示例吗?

在更基础的层面上,您可以查看 jQuery 核心样式指南: http ://docs.jquery.com/JQuery_Core_Style_Guidelines

In this other thread ther are some good points about style of jQuery use: How can I organize the jQuery code style to avoid confusion by so many brackets and so many nests? Any good sample?

At a more basic level you could have a look at the jQuery core style guidelines: http://docs.jquery.com/JQuery_Core_Style_Guidelines

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文