2012-02-13 172 views
0

我正在使用$('.startb').click(function() { var myId = $(this).attr("id"); });来捕获id“startb1”我需要添加什么,以便通过使用事实它们都在同一个div中的类“flashObj”来捕获id“test1”容器“audioContainer”通过点击获取div ID

<div class="audioContainer"> 
      <div class="audioTitle">hi</div> 
      <div class="playerHolder"> 
      <div class="startb" id="startb1" rel="Audio/004_IAM_God_is_Love.mp3"><img src="dbs/images/start.png" width="40" height="40" /></div> 
      <div class="flashObj" id="test1"></div> 
      <div class="mp3Logo"><a href="Audio/004_IAM_God_is_Love.mp3"><img src="dbs/images/mp3_off.gif"/></a></div> 
      </div> 
</div> 

回答

2

你可以搜索具有类flashObj股利的兄弟姐妹:

$('.startb').click(function() { 
    var myId = $(this).attr("id"); 
    var flashObjID = $(this).siblings('.flashObj').attr('id'); 
}); 
+0

dang击败了我。我会用这个片段。 – Jlange 2012-02-13 23:15:24

2
var myId = this.id; 
var otherId = this.parentNode.querySelector(".flashObj").id; 

让“startb1” id为约150倍比你的更有效,由于jQuery有要经过刚创建$(this)对象的步骤数量的这种方法顺便一提。

另外,IE8支持querySelector,而getElementsByClassName则不支持。

如果需要IE7及以下版本,并且结构可靠(即它总是您需要的第四个孩子div),请使用:var otherId = this.parentNode.children[3].id;

+0

+1使用更为高效'this.id '而不是详细和低效的$(this).attr(id)' – RobG 2012-02-14 01:21:29

0

假设你想使用相同的“click”事件,下面应该做的伎俩:

$('.startb').click(function() { 
    var myId = $(this).attr("id"); 
    var flashID = $(this).parent().find(".flashObj").attr("id"); 
}); 
1

如果您使用的是最新的jQuery版本,请使用.on()而不是.click():

$(".audioContainer").on("click", ".startb", function(e){ 
    var _this = $(this); 
    var id = _this.attr("id"); 
    var oId = _this.closest(".audioContainer").find(".flashObj").attr("id"); 
} 

否w ^你也可以映射多个事件时,请对后来事件,甚至可以将数据传递到event.data对象等

更多详情:jQuery .on()