在jQuery中基于ID调用函数 [英] Calling a function based on an ID in jQuery

查看:457
本文介绍了在jQuery中基于ID调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下功能:

$('#topic').change(function()

它作用于称为#topic的ID.我想对名为

It acts on an ID that's called #topic. I would like to make this act on an ID called

#topic_1 or #topic_2 or #topic_3 etc. 

有没有一种简单的方法可以使用通配符使用jQuery?另外,我如何提取数字1,2或3并找出另一个标记为key_1,key_2或key_3的元素的值.我希望这对您有意义.

Is there a simple way to do this with jQuery using wildcards? Also how can I extract the number 1,2 or 3 and find out the value of another element labeled key_1, key_2 or key_3. I hope this makes sense to you.

对不起,这是一个基本问题,但是我对jQuery完全陌生

Sorry it's a basic question but I am totally new to jQuery

推荐答案

如果愿意,您可以使用id(下面有更多选项),使用选择器开头:

You can use id if you like (more options below), using the "attribute starts with" selector:

$('[id^="topic"]').change(function() { ... });

该选择器将匹配"topic"开头的任何id值.确保将参数(主题")用引号引起来,(现在)是必需的.

That selector will match any id value that starts with "topic". Be sure to put the argument ("topic") in quotes, it's (now) required.

如果您有这些的简短列表,则可以选择直接将它们直接列出:

If you have a short list of these, you may choose to simply list them directly:

$('#topic1, #topic2, #topic3').change(function() { ... });

或者您可以选择它们共有的其他特征.热门选择:

Or you might choose some other characteristic they have in common. Popular choices:

$('.theClass').change(...);

  • 它们在DOM中的位置.例如,如果要监视表单中所有字段上的change事件,则可以从表单开始并使用后代选择器,也许带有 :input 这样的限定词(与inputselecttextarea元素匹配),如下所示:

  • Their location in the DOM. For instance, if you want to watch the change event on all fields in a form, you can start with the form and use a descendant selector, perhaps with a qualifier like :input (which matches input, select, and textarea elements), like this:

    $('#formId :input').change(...);
    

  • 他们使用属性等于"选择器共享的其他一些属性属性包含" 选择器,等等.

  • Some other attribute they share, using an "attribute equals" selector, "attribute contains" selector, etc.

    如您所见,您有有很多选择,而不仅仅是ID和类.请注意,在大多数浏览器中,类选择器将是最快的,但这仅在非常复杂的页面上或当您在选择器中查找 lot 时才真正重要.一如既往地优化是否/何时遇到问题.

    As you can see, you have a lot to choose from, far more than just IDs and classes. Note that on most browsers, class selectors will be the fastest, but this only really matters on very complex pages or when you're looking up selectors a lot. Optimize if/when you see a problem, as always.

    这篇关于在jQuery中基于ID调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆