JQuery:为什么使用不显眼的 JavaScript/Document Ready 函数而不是 OnClick 事件?

发布于 2024-07-14 11:42:32 字数 1862 浏览 7 评论 0 原文

我刚刚开始研究 JQuery。 目前我的网络应用程序中没有任何 AJAX。

我的 HTML 中现有的 JavaScript 如下所示:

<form ...>
<p>Find what? <input ...></p>
<div class="ButtonArray">
  <a href="AddRecord.ASP&amp;Action=ADD">ADD</a>
  <a href="#" onClick="return MyFormSubmit();">FIND</a>
</div>
</form>

这显示 [添加] 和 [查找] 按钮。 对于“查找”,需要提交表单,我使用 MyFormSubmit() 来验证数据,向页面添加视觉效果,然后发布数据。

我可以为“查找”按钮添加一个 CLASS 或 ID,在 JQuery 中我可以编写如下内容:

$(function() {
  $(".MySearchButtonClass").click(function() {
    // validate and process form here
  });
});

在我理解 JQuery 的“新手”阶段,我不明白为什么我要这样做 我的旧方法

识别对象附近的方法。 可能存在用户按下按钮之前 JS 尚未加载的风险(有吗?JS 的 LOAD 就在页面顶部)。

在加载文档之前,JQuery Document Ready 方法不会被激活(我认为这保证了 JS 全部存在并准备好运行?),但它将代码移动到 HTML 文件的单独部分 - 所以当我在 HTML 源代码中看到 MyButtonArray DIV,但我不清楚哪些对象有方法,哪些没有。

您能帮助我了解我的选择是什么以及我应该注意的好处/陷阱吗?

编辑:我很满意 DOM 操作(例如单击任何“LightBoxThumb”类的缩略图时可能出现的 LightBox)将使用 Unobtrusive Javascript。

然而,我正在努力说服自己,具有特定操作的按钮应该以这种方式应用其方法。 (除了对“其他地方”的某个函数调用之外,我当然不会在按钮上放置任何代码,但在我看来,这是我了解该按钮功能的最佳线索,并且不显眼的 Javascript 层可能会使这变得更加困难来确定。)

Edit2 - 接受的答案

我已经接受了 Russ Cams 的答案。 它描述了 Unobtrusive Javascript,这种方式有助于我更多地了解如何使用 JavaScript。 什么时候应该使用它。

目前(当我有更多经验时可能会改变!)我将坚持使用 OnClick 事件来对对象进行单个、不变的操作,因为我觉得这样更容易调试 - 并诊断是否出现问题。 对于允许单击标题列进行排序(以及该类型的情况)的表格上的 ZebraStripes,我可以看到不显眼的 Javascript 方法的好处,

Russ 的最终评论特别有帮助,在此重复:

“@Kristen - 你是对的,就像很多人一样 编程主题,还有更多 不止一种方法,人们就会 坚决坚持自己的信念! 如果 我们谈论的是单一方法 对于单个按钮,我完全 了解你来自哪里...

如果我们谈论很多 JavaScript,具有相同的函数调用 对于多个元素,不同 函数调用不同的方法, 等等,我认为这会更多 自己很难内联混音 和不引人注目的方法,而且它 最好采用其中之一或 其他方法”

I've just started looking at JQuery. I don't have any AJAX in my web application at present.

My existing JavaScript in my HTML looks like:

<form ...>
<p>Find what? <input ...></p>
<div class="ButtonArray">
  <a href="AddRecord.ASP&Action=ADD">ADD</a>
  <a href="#" onClick="return MyFormSubmit();">FIND</a>
</div>
</form>

This displays Buttons for [Add] and [Find]. For Find it is necessary to Submit the form, and I use MyFormSubmit() which validates the data, adds a visual effect to the page, and then POSTs the data.

I could add a CLASS or ID to the for the Find button and in JQuery I could write something like:

$(function() {
  $(".MySearchButtonClass").click(function() {
    // validate and process form here
  });
});

At my "novice" stage of understanding with JQuery I don't get why I would do it this way

My old way identifies the Method near the object. There may be a risk that the JS has not loaded before the user presses the button (is there? The LOAD for the JS is right at the top of the page).

The JQuery Document Ready method won't be activated until the document is loaded (which I assume guarantees that the JS is all present and ready to be run?), but it moves the code to a separate part of my HTML file - so when I see the MyButtonArray DIV in the HTML source it isn't obvious to me which objects have methods, and which do not.

Can you please help me understand what my options are and the benefits / gotchas that I should look out for?

Edit: I'm comfortable that DOM manipulation - such as a LightBox that can appear when any thumbnail with class "LightBoxThumb" is clicked - would use Unobtrusive Javascript.

However I am struggling to persuade myself that a button that has a specific action should have its method applied in that way. (I certainly wouldn't put any code on the button other than a single function call to something "elsewhere", but to my mind that is my best clue as to what that button does, and layers of Unobtrusive Javascript may make that much harder to determine.)

Edit2 - Accepted Answer

I've taken Russ Cams answer. It describes Unobtrusive Javascript in a way that has been helpful to me in understanding more about how & when that should be used.

For the moment (may change when I have more experience!) I'll stick with an OnClick event for a single, non-changing, action on an object as I feel that will be easier for me to debug - and diagnose if problems arise. For ZebraStripes on a table that allows click on heading column to sort (and situations of that type) I can see the benefits of the Unobtrusive Javascript approach

Russ's final comment was particularly helpful, repeated here:

"@Kristen - You're right, like a lot
of programming topics, there is more
than one approach and people will
vehemently stand by their beliefs! If
we're talking about a single method
for a single button, I totally
understand where you're coming from...

If we're talking about lots of
JavaScript, with same function calls
for more than one element, different
function calls for different methods,
etc. I think that it would be more
difficult for oneself to mix inline
and unobtrusive approaches, and it
would be better to adopt one or the
other approach"

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

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

发布评论

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

评论(4

踏月而来 2024-07-21 11:42:33

文档就绪事件发生在文档加载事件之前。 加载 DOM 后就会发生文档就绪,这样所有元素在开始处理它们之前就已存在。

所以,是的,JS 将在文档渲染时准备就绪。 关于绑定的另一点是,当发生某些操作时,它对于更改元素的绑定很有用。

如果您愿意,您仍然可以在元素上声明操作。

the document ready event is well before the document load event. document ready occurs once the DOM is loaded which is so that all the elements exist before you start working on them.

So yes the JS will be ready as the document is rendered. The other point about binding is that it is useful for changing bindings to elements when cetain actions occur.

You can still declare the action on the element if you prefer though.

夏日浅笑〃 2024-07-21 11:42:33

随着时间的推移,我认为您会习惯 jQuery 语法并阅读:

class="MyFormSubmit" 变得与阅读 onClick="return MyFormSubmit(); 一样提供信息,

其中力量真正开始发挥作用(除了其他海报提到的所有好处之外) )是您可以轻松地通过与网页上其他操作相关的选择器来更改 onClick 绑定,而这种方式最初似乎从未出现过,

我问自己的一个问题是,如果我打算使用任何新工具,那么我打算深入使用该工具。我计划广泛使用框架或库,然后以“更本机”的编码风格编写代码将变得更加自然,并且了解该工具的其他开发人员会发现代码更干净且更易于理解。

Over time I think you get used to the jQuery syntax and reading:

class="MyFormSubmit" becomes as informative as reading onClick="return MyFormSubmit();

Where the power really starts to kick in (aside from all the benefits mentioned by other posters) is the ease with which you could change the onClick binding via selectors tied to other actions on the web page in ways that never seem to present themselves initially.

One question I ask myself is how deep I plan on going with any new tool, if I am planning to make extensive use of a framework or library then writing my code in it's "more native" coding style will become a lot more natural and other developers that know the tool will find the code a lot cleaner and more understandable.

深海不蓝 2024-07-21 11:42:33

您可以通过这种方式将 UI 逻辑与实际的 HTML 设计分开。

You do it this way to seperate the UI logic from the actual HTML design.

锦欢 2024-07-21 11:42:32

Unobtrusive JavaScript 是将 JS 代码与标记分离的主要驱动力

  • 功能(“行为层”)与网页的分离
    结构/内容和呈现
  • 避免传统 JavaScript 问题的最佳实践
    编程(例如浏览器
    不一致和缺乏
    可扩展性)
  • 逐步增强以支持可能不支持的用户代理
    高级 JavaScript 功能

使用 document.ready 中的代码,直到 DOM 加载并且页面内容加载之前,它才会执行

学习 jQuery

使用 $(document).ready(),您可以在窗口加载之前加载或触发事件或您希望它们执行的任何操作。

您可能想看看jQuery in Action,我强烈建议推荐它。 您可以参考第 1 章 rel="nofollow noreferrer">图书主页。 我认为这样做可以进一步了解为什么分离可以发挥作用。

最后,看看这个问题 其中的答案详细说明了如何在 DOM 节点上找到事件侦听器。

编辑:

一些想法可能会说服您为什么不引人注目的 JavaScript 是一个好主意。

想象一下,您有一个函数绑定为事件处理程序,用于在多个元素中的每个元素上引发的同一事件 -

  • 找出哪个元素会更容易吗?
    元素调用该函数来处理
    声明内联时发生的事件
    在每个元素或声明中
    是在一个地方,在
    标记?

  • 如果你想添加到
    调用该函数的元素
    该事件是在他们每个人身上引发的吗?
    添加以下内容会更容易/更好吗
    事件处理程序内联到每个元素
    或者在一处更改代码?

Unobtrusive JavaScript is the main driver for separating JS code from markup

  • Separation of functionality (the "behavior layer") from a Web page's
    structure/content and presentation
  • Best practices to avoid the problems of traditional JavaScript
    programming (such as browser
    inconsistencies and lack of
    scalability)
  • Progressive enhancement to support user agents that may not support
    advanced JavaScript functionality

With the code in document.ready, it will not execute until the DOM has loaded and before the page contents are loaded

From Learning jQuery

With $(document).ready(), you can get your events to load or fire or whatever you want them to do before the window loads.

You may want to take a look at jQuery in Action, I'd highly recommend it. You can sample Chapter 1 and Chapter 5 on the book's homepage. I think doing so may provide further insight into why separation can work well.

Finally, have a look at this question which has answers that detail how you would find the event listeners on a DOM node.

EDIT:

Some thoughts which may persuade you why unobtrusive JavaScript can be a good idea.

Imagine that you have a function bound as an event handler for the same event raised on each of a number of elements -

  • Would it be easier to find out which
    elements call that function to handle
    an event when the declaration is inline
    in each element, or the declaration
    is in one place, outside of the
    markup?

  • What if you want to add to the
    elements that call that function when
    the event is raised on each of them?
    Would it be easier/better to add the
    event handler inline to each element
    or to change the code in one place?

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