开发者

How to get the span id which starts with a word

actually i have two span with ids like this date_eform and time_eform.

Now i have to get these ids.. and check if the span id starts with date_ then i have to perform some logic. and if span id starts with time_ then another action.

 <span id='date_eform'></span><span id='time_eform'></span>

Pl开发者_StackOverflow社区ease help me in this.


you need starts with selector

so

$.each('span[id^="date_"]',function(){
   //your code here
});

and

$.each('span[id^="time_"]',function(){
   //your code here
});


Try this:

$("span[id^='date_']").something...    
$("span[id^='time_']").something-else...


This should work:

$("span[id^={word}]")

Where {word} is the word you want the element id to start with.

The following like will help: http://api.jquery.com/attribute-starts-with-selector/


this should do it:

$('[id^="date_"]')


jQuery syntax for attribute ends with:

$('span[id$="_eform"]')

jQuery syntax for attribute starts with:

$('span[id^="_eform"]')

jQuery syntax for attribute contains:

$('span[id*="_eform"]')

From what I understand, you should need to do something like:

$('span[id$="_eform"]')

Then, with an each method, test if jQuery-object ids are date or time.

var elements = $('span[id$="_eform"]');
elements.each(function() {
    if(this.id.substring(0,5)=='date') {
        // handle dates
    } else if(this.id.substring(0,5)=='time_') {
        // handle times
    }
});


You can use a variety of ways to achieve this, most of those questions are listed in the other answers.

However, if you only have 2 elements, why aren't you just accessing them directly with the ID? Maybe you want to do something to them once an action has been carried out on them? In which case all the methods listed here can't be used.

If you simply want to bind the two selectors you can just use

$('#date_eform, #time_eform')...

What you're asking for doesn't make too much sense in the context of your question. If you add more details, there may be a better way to do what you're asking for.


I suggest you use id and class for this task; it would make it clearer. Example below:

HTML:

<span id='date' class='eform'></span>
<span id='time' class='eform'></span>

JavaScript (using jQuery):

$(".eform").each(function() {
    switch (this.id) {
    case "date":
        // do something
        break;

    case "time":
        // do something
        break;

    default:
        // "id" is not a case
    }
});

Example here: http://fiddle.jshell.net/9hcfx/

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜