在负载上定位子元素的更有效方法(More efficient way of targeting child element on load)

编程入门 行业动态 更新时间:2024-10-23 21:31:42
负载上定位子元素的更有效方法(More efficient way of targeting child element on load)

在许多情况下,我在表单中使用jQuery的真棒日期选择器 。 我想要一种通用的方法来应用它,而不知道输入的id或类是什么。 我想出了这个:

<span id="datePickerChild"> <input type="text"/> </span> <script type="text/javascript"> $(document.getElementById("datePickerChild").firstChild).datepicker(); </script>

使用mvc3框架,这些输入可以在运行时根据帮助程序输入,因此我想要这种动态方法。 有没有更有效的方法来做到这一点?

编辑:

使用jQuery 1.4.4

In many cases, I use jQuery's awesome datepicker in forms. I wanted a generic way to apply it without knowing what the id or class of the input would be. I came up with this:

<span id="datePickerChild"> <input type="text"/> </span> <script type="text/javascript"> $(document.getElementById("datePickerChild").firstChild).datepicker(); </script>

Using the mvc3 framework these inputs get put in with their own ids and such at runtime based on the helpers so I wanted this dynamic approach. Is there a more efficient way to be doing this?

Edit:

Using jQuery 1.4.4

最满意答案

这似乎是一种合理的方法。 您可以使用jQuery“idiomatically”更多地执行此操作,如下所示:

$('#datePickerChild').children().first().datepicker();

甚至:

$('#datePickerChild > input:first').datepicker();

然而,有一点令人困惑的是,你说你想要这样做而不必知道元素的id是什么,尽管你仍然在选择器中使用id。 如果你试图“通常”使用那个id(就像在页面上多次出现一样),你会想要使用一个类。 在您需要的元素上有一个类之后,您只需将选择器更改为:

$('.date-picker-container').children().first().datepicker();

That seems like a reasonable approach for this. You could probably do it a little more "idiomatically" with jQuery like the following:

$('#datePickerChild').children().first().datepicker();

Or even:

$('#datePickerChild > input:first').datepicker();

One point of confusion, however, is that you say you want to do this without having to know what the id of the element is, although you still use an id in the selector. If you're trying to use that id "generically" (as in it appears several times on the page), you would want to use a class instead. Once you have a class on the element you need, you would just change your selector to something like:

$('.date-picker-container').children().first().datepicker();

更多推荐

本文发布于:2023-08-04 23:52:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1424264.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:负载   位子   更有效   元素   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!