最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery selector: Select multiple ID and get their values - Stack Overflow

programmeradmin1浏览0评论

I am looking for a way to extract a part of an ID and use it in my script.

My HTML:

<div id="item1"></div>
<div id="item2"></div>
<div id="item3"></div>
<div id="item4"></div>
<div id="item5"></div>

My jQuery:

$('#item(1|2|3|4|5)').mouseout(function(event) {

    //Get the number of the item (1,2,3,4,5)
    item_number = ???

    alert(item_number);


    }

How can achieve this using jQuery?

I am looking for a way to extract a part of an ID and use it in my script.

My HTML:

<div id="item1"></div>
<div id="item2"></div>
<div id="item3"></div>
<div id="item4"></div>
<div id="item5"></div>

My jQuery:

$('#item(1|2|3|4|5)').mouseout(function(event) {

    //Get the number of the item (1,2,3,4,5)
    item_number = ???

    alert(item_number);


    }

How can achieve this using jQuery?

Share Improve this question asked Apr 16, 2013 at 22:32 Peter LurPeter Lur 7582 gold badges13 silver badges27 bronze badges 1
  • 4 Don't do that. Those items should be <div class="item" data-id="1"></div> <div class="item" data-id="2"></div> ...etc... – zzzzBov Commented Apr 16, 2013 at 22:35
Add a ment  | 

3 Answers 3

Reset to default 5

Additionally to what VisioN said. I would like to encourage you to use classes for this purpose:

<div class="item" id="item1"></div>
<div class="item" id="item2"></div>
<div class="item" id="item3"></div>
<div class="item" id="item4"></div>
<div class="item" id="item5"></div>

And

$(".item").mouseout(...)

You can use starts with selector:

$("[id^='item']").mouseout(function(e) {
    var item_number = this.id.replace("item", "");
    alert(item_number);
});

A simple way to do that is here:

$('div').mouseout(function() {
    var this_id = $(this).attr('id');
    alert(this_id);
});

If you want to make sure not all divs get alerted, give all of those divs a class and use this instead:

$('.myClass').mouseout(function() {
    var this_id = $(this).attr('id');
    alert(this_id);
});
发布评论

评论列表(0)

  1. 暂无评论