简体   繁体   English

如何优化我的JavaScript?

[英]How to optimize my javascript?

I have inherited a piece of code which has a series of functions like the following: 我继承了一段代码,其中包含一系列功能,如下所示:

$("#data[User][notify_one_day_out]").change(function () {
    $("#updatenotificationsform").submit();
}

$("#data[User][notify_one_month_out]").change(function () {
    $("#updatenotificationsform").submit();
 }

and this goes on and on. 而且这种情况一直持续下去。 How do I just write one function that does the same thing since every ID begins with data. 由于每个ID都以数据开头,因此我该如何编写一个执行相同功能的函数。 Sorry am a JS newbie 抱歉,JS新手

Thanks 谢谢

Something like this would probably work for you: 这样的事情可能会为您工作:

$('[id^="data"]').change(function() {
 $("#updatenotificationsform").submit();
}

That basically says: grab all the elements with an Id starting with the string "data", you can read more about that here: http://api.jquery.com/attribute-starts-with-selector/ 基本上就是这样:以字符串“ data”开头的ID抓取所有元素,您可以在此处阅读有关此内容的更多信息: http : //api.jquery.com/attribute-starts-with-selector/

Let me know if that helps! 让我知道是否有帮助!

Edit 编辑

Alternatively if you can modify your mark up, you could assign the same class to all those elements, and then just select using the class selector. 或者,如果您可以修改标记,则可以为所有这些元素分配相同的类,然后仅使用类选择器进行选择。

In addition to @Deleteman's sound advice, remember that you can specify multiple selectors for $() , eg: 除了@Deleteman的声音建议外,请记住,您可以为$()指定多个选择器,例如:

$(  "#data[User][notify_one_month_out]",
    "#data[User][notify_one_day_out]",
    "#some-other-selector",
    // ...
).change(function () {
  $("#updatenotificationsform").submit();
}

You can actually stack up those Jquery selectors would that be enough of a help or do you really have ALOT of them? 实际上,您可以堆叠那些Jquery选择器就足够了,还是您真的有很多选择器?

$("#data[User][notify_one_day_out], #data[User][notify_one_month_out]").change(function ()     
{
    $("#updatenotificationsform").submit();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM