开发者

Calling a function based on an ID in jQuery

I have the following function:

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

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. 

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

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


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

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

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:

  • Their class, using the class selector:

    $('.theClass').change(...);
    
  • 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.

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.


Why not use a class selector instead? Gives all the elements a CSS class called "topic" and modify your code as follows:

$('.topic').change(function() { });


Like this

$('input[id^="topic"]').val('news here!');

$(input[id^="topic"]).change(function(){

  //Do something

 });


use class attribute..

$('.topic').change(function() { });


Using a class selector is preffered way to do it. However, for arbitrary names you can also implement something similar to this:

for (i=0;i<blahblah;i++){
$("#topic_"+i).change(function() {}); }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜